如何使用嵌套try-except选择要读取的文件



根据可用性,我正在尝试定义要读取的文件的优先级。我使用了嵌套的Try-Except,它按预期工作。然而,它相当麻烦。

try :
data_bachir = pd.read_table(model_data_path_1, nrows=73, infer_datetime_format = True, parse_dates = ["DATE"], sep='s+',  engine='python') 
Tmax_bachir = str(max(data_bachir.T2M.loc[0:23]))
except :
try :
data_bachir = pd.read_table(model_data_path_2, nrows=73, infer_datetime_format = True, parse_dates = ["DATE"], sep='s+',  engine='python') 
Tmax_bachir = str(max(data_bachir.T2M.loc[0:12])) 
except :    
try:
data_bachir = pd.read_table(model_data_path_3, nrows=73, infer_datetime_format = True, parse_dates = ["DATE"], sep='s+',  engine='python') 
Tmax_bachir = str(max(data_bachir.T2M.loc[12:36])) 
except : 
data_bachir = pd.read_table(model_data_path_4, nrows=73, infer_datetime_format = True, parse_dates = ["DATE"], sep='s+',  engine='python') 
Tmax_bachir = str(max(data_bachir.T2M.loc[23:47]))

还有比蟒蛇更优雅的方式吗?

另一种更紧凑、可扩展的方法,使用列表+循环:

import os

def find_existing_sourcefile(file_list):
for file in file_list:
if os.path.isfile(file):
return file
return None  # if loop ends without returning something, this is returned.
def do_pandas_stuff():
file_list = ['model_data_path_1', 'model_data_path_2', 'model_data_path_3', 'model_data_path_4']
file = find_existing_sourcefile(file_list)
try:
data_bachir = pd.read_table(file, nrows=73, infer_datetime_format = True, parse_dates = ["DATE"], sep='s+',  engine='python') 
Tmax_bachir = str(max(data_bachir.T2M.loc[0:23]))
except:   # would be better to use named exceptions here.
print("No valid source file found")

do_pandas_stuff()

最新更新