0

I am looping over many files in folder A and folder B to do some operations on the merged data frame of A_file1 and B_file1; A_file2 and B_file2 etc.

for a in A_list:
     for b in B_list:
         A_file = pd.read_csv(f'A_file{a}.csv')
         B_file = pd.read_csv(f'B_file{b}.csv')
         new_file = pd.merge(A_file, B_file, on="common_var", how='left')
         new_file.to_csv(f'new_file{a}_{b}.csv')

How do I make the loop continue if either A_file or B_file does not exist for a particular {a} or {b}? (And just not create an {a}_{b} file if either {a} or {b} does not exist?)

pandini
  • 69
  • 7
  • Are you getting an error when you encounter files that do not exist? If so, please include the stacktrace. – PacketLoss Feb 03 '20 at 03:51
  • You could use a [Try/Catch block as done in this exaple reading CSV into Dataframes](https://stackoverflow.com/questions/42143249/how-to-not-read-csv-if-csv-is-empty) – DarrylG Feb 03 '20 at 03:56

1 Answers1

1

You could use try/except like so:

for a in A_list:
    for b in B_list:
        try:
            A_file = pd.read_csv(f'A_file{a}.csv')
            B_file = pd.read_csv(f'B_file{b}.csv')
            new_file = pd.merge(A_file, B_file, on="common_var", how='left')
            new_file.to_csv(f'new_file{a}_{b}.csv')
        except:
            print ("Either file A or file B is missing")
Sameeresque
  • 2,464
  • 1
  • 9
  • 22