Search code examples
pythonexceptionerror-handlingtry-catchexcept

how to chose files to read from using nested try except?


Depending on availability, I am trying to define a priority order of files to read from. I used nested Try Except and it works as expected. However, it's pretty cumbersome.

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]))

Is there a more elegant pythonic way to do this?


Solution

  • Another, compacter and scaleable approach, using list+loop:

    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()