Python:如果文件不存在,如何继续循环遍历多个 csv
Python: How to continue loop over many csv if file does not exist
我正在遍历文件夹 A 和文件夹 B 中的许多文件,以对 A_file1 和 B_file1 的合并数据框进行一些操作; A_file2 和 B_file2 等等
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')
如果特定 {a} 或 {b} 不存在 A_file 或 B_file,我该如何继续循环? (如果 {a} 或 {b} 不存在,就不要创建 {a}_{b} 文件吗?)
您可以像这样使用 try/except:
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")
我正在遍历文件夹 A 和文件夹 B 中的许多文件,以对 A_file1 和 B_file1 的合并数据框进行一些操作; A_file2 和 B_file2 等等
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')
如果特定 {a} 或 {b} 不存在 A_file 或 B_file,我该如何继续循环? (如果 {a} 或 {b} 不存在,就不要创建 {a}_{b} 文件吗?)
您可以像这样使用 try/except:
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")