【问题标题】:Python: How to continue loop over many csv if file does not existPython:如果文件不存在,如何继续循环遍历多个 csv
【发布时间】:2020-02-03 03:48:44
【问题描述】:

我正在遍历文件夹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} 文件?)

【问题讨论】:

标签: python loops csv skip


【解决方案1】:

你可以像这样使用 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")

【讨论】:

  • 应该使用特定的例外 - except FileNotFoundError: #...
猜你喜欢
  • 2019-12-13
  • 2019-07-21
  • 1970-01-01
  • 2022-12-12
  • 2021-04-17
  • 2020-06-25
  • 2014-04-10
  • 1970-01-01
  • 2019-11-20
相关资源
最近更新 更多