【问题标题】:Python: ignore filenotfound and other errors in pandas/python codePython:忽略 pandas/python 代码中的 filenotfound 和其他错误
【发布时间】:2020-05-20 02:48:25
【问题描述】:

我写了一段代码,其结构基本如下:

第 1 步:导入库

第二步:读取多个输入文件

>>>os.getcwd()
'C:\\Users\\User\\Downloads\\Input\\Daily'

>>>df_delhi = pd.read_excel("Delhi.xlsx")
>>>df_mea = pd.read_excel("MEA.xlsx",sheet_name='MTD NSV_Volumes',usecols ='B:D', skiprows=3)

第 3 步:对每个文件进行计算

第四步:输出到excel文件中。

我这里有个条件。在 20 个奇怪的文件中,如果缺少任何一个文件,我需要忽略它并继续编写代码。我还需要忽略该文件中稍后在代码中出现的计算。

我如何做到这一点?

不确定是否需要在此处粘贴任何代码,因为它只是基本的文件读取和计算

【问题讨论】:

  • 读取多个输入文件,是来自不同的文件夹还是任何包含要读取的文件列表的文本文件。
  • 它只是一个包含多个文件的文件夹。
  • 那么,你使用os.listdir阅读文件?
  • 更新了我的问题,有帮助吗?

标签: python pandas dataframe exception


【解决方案1】:

查看异常(官方 Python 教程:https://docs.python.org/3/tutorial/errors.html)。通过期待并捕获FileNotFoundError,您可以巧妙地忽略该文件,而只处理您找到的文件。

【讨论】:

    【解决方案2】:

    看起来你需要遍历一个目录并读取其中的可用文件。

    import os
    import pandas as pd
    
    # each file get's different argument's while reading..
    file_params = {
        "Delhi.xlsx": {},
        "MEA.xlsx": {"sheet_name": 'MTD NSV_Volumes', 'usecols': 'B:D'},
    }
    
    data = {}
    for file_ in os.listdir('C:\\Users\\User\\Downloads\\Input\\Daily'):
        data[file_.replace(".xlsx", "")] = pd.read_excel(file_, **file_params.get(file_, {}))
    
    # dataframe's contained inside dict.
    # data['Delhi'], data['MEA']....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 2015-11-14
      • 2018-04-06
      • 1970-01-01
      • 2018-11-24
      • 2018-06-21
      • 2013-03-11
      相关资源
      最近更新 更多