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

2

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Should use specific exception - except FileNotFoundError: #...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.