I've written a small programme to check the directory, where the programme is located, for a subdirectory named "lookup_tables" and open the found lookup tables as separate data frames. I know the names of the lookup tables but would like to catch the exception, that these names, i. e. files, are not found in the directory. In order to do that I'd think that a try-statement would be more sufficient, than an if-statements. However, I dont't get my head around any idea how to achieve this. So in short: I would like to learn how to change a programme like this, so the list tables with the datas directory+name is not beeing handled by if-clauses, but try-statements, so I then can raise an error, if there is no lookup table to be found.
import os, sys
import pandas as pd
def find_lookup_tables():
gspek_found = False
pt_found = False
# programmes directory
py_path = os.path.dirname(sys.argv[0])
# open py_path and search it for all its contents, then write all found
# data in the folder "lookup_tables" into a list
tables = [os.path.join(root, name) for root, dirs, files in os.walk(py_path)
for name in files if "lookup_tables" in root.lower()]
# search all found tables for the gspek and the pt lookup tables and save
# them as data frames
for table in tables:
if "gspek" in table.lower():
df_gspek = pd.read_csv(table, index_col = 'Index')
gspek_found = True
if "pt" in table.lower():
df_pt = pd.read_csv(table, index_col = 'Index')
pt_found = True
return(df_gspek, df_pt, gspek_found, pt_found)
df_gspek, df_pt, gspek_found, pt_found = find_lookup_tables()
#print all return values
print(df_gspek.head())
print(df_pt.head())
print ""
print("gspek_found: {}".format(gspek_found))
print("pt_found: {}".format(gspek_found))
Here is the output:
Gspek
Index
0 10
1 20
2 30
3 40
4 50
P t 1/(P*t)
Index
0 0.2 5.0 1
1 0.5 1.0 0.5
2 0.8 1.0 1.25
3 0.4 0.2 12.5
4 0.1 0.2 50
gspek_found: True
pt_found: True
Aucun commentaire:
Enregistrer un commentaire