【问题标题】:"No such file or directory exist", but it obviously does“不存在这样的文件或目录”,但显然确实存在
【发布时间】:2021-09-27 15:39:53
【问题描述】:

我正在尝试将多个 excel 文件导入 DataFrame,但出现错误:FileNotFoundError: [Errno 2] No such file or directory: 'test1.xlsx'

代码:

path=os.getcwd()
files = os.listdir(path+"/testimport")

df = pd.DataFrame()

for f in files:
    data = pd.read_excel(f,
                           sheet_name = "Data",
                           skiprows = range(0, 4),
                           usecols = "B:I,P:V")
    df = df.append(data)

但是,当我尝试打印文件时,它确实有效:

in:    for f in files:
        print(f)
        
out:    test1.xlsx
        test2.xlsx

这怎么可能以及如何解决?我尝试了绝对路径,但结果相同。

【问题讨论】:

  • read_excel 提供完整路径listdir 只返回文件名。
  • 也许是pd.read_excel(path + "/testimport/" + f, ,因为看起来f 只包含文件名,而不是完整路径。

标签: python pandas import-from-excel


【解决方案1】:

您应该提供输入文件的完整路径(包括目录名称)。目前,您只提供文件名。因此,读取的行应如下所示:

data = pd.read_excel(os.path.join(path, "testimport", f), sheet_name = "Data", skiprows = range(0, 4), usecols = "B:I,P:V")

注意:os.path.join 是连接目录/文件名的更安全的方法,否则在额外的正斜杠或在不同操作系统中运行时,您的代码将容易出错。

【讨论】:

    【解决方案2】:

    除了发布的答案之外,您实际上可以使用scandir 而不是listdir 来简化代码,这会产生DirEntry 对象,这些对象的完整路径可用作path 属性

    import os
    
    df = pd.DataFrame()
    
    for f in os.scandir(os.path.join(os.getcwd(), "testimport")):
        data = pd.read_excel(
            f.path,
            sheet_name="Data",
            skiprows=range(0, 4),
            usecols = "B:I,P:V"
        )
        df = df.append(data)
    

    【讨论】:

      【解决方案3】:

      您还可以更改当前工作目录os.chdir('./testimport')

      os.chdir('./testimport')
      path=os.getcwd()
       
      files = os.listdir(path)
       
      df = pd.DataFrame()
       
      for f in files:
          data = pd.read_excel(f,
                                 sheet_name = "Data",
                                 skiprows = range(0, 4),
                                 usecols = "B:I,P:V")
          df = df.append(data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多