【问题标题】:Python File Not Found Error even though file is in same directoryPython File Not Found Error 即使文件在同一目录中
【发布时间】:2020-04-01 06:23:38
【问题描述】:

我正在运行一个python代码(文件名-images.py),它读取-

    import gzip
    f = gzip.open('i1.gz','r')

但它显示 FileNotFoundError。 我的包含 images.py 的文件夹看起来像-

New Folder/
   images.py
   i1.gz
   (...Some other files...)

【问题讨论】:

  • 尝试使用绝对路径
  • 是否正在从文件夹New Folder 中运行images.py

标签: python file-not-found


【解决方案1】:

问题是您没有从New Folder 中运行脚本。 您可以通过使用绝对路径轻松解决它,而无需对其进行硬编码:

from os import path
file_path = path.abspath(__file__) # full path of your script
dir_path = path.dirname(file_path) # full path of the directory of your script
zip_file_path = path.join(dir_path,'i1.gz') # absolute zip file path

# and now you can open it
f = gzip.open(zip_file_path,'r')

【讨论】:

    【解决方案2】:

    通过执行以下操作检查脚本的当前工作目录:

    import os
    os.getcwd()
    

    然后,将此与您的 i1.gz 绝对路径进行比较。然后你应该可以看看有没有不一致的地方。

    【讨论】:

      【解决方案3】:

      您是从New Folder 运行脚本吗?

      如果你在文件夹中,它应该可以工作:

      c:\Data\Python\Projekty\Random\gzip_example>python load_gzip.py
      

      但如果您从具有文件夹名称的父文件夹运行脚本,则会返回错误:

      c:\Data\Python\Projekty\Random>python gzip_example\load_gzip.py
      Traceback (most recent call last):
        File "C:\Data\Python\Projekty\Random\gzip_example\load_gzip.py", line 2, in <module>
          f = gzip.open('file.gz', 'r')
        File "C:\Python\Python 3.8\lib\gzip.py", line 58, in open
          binary_file = GzipFile(filename, gz_mode, compresslevel)
        File "C:\Python\Python 3.8\lib\gzip.py", line 173, in __init__
          fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
      FileNotFoundError: [Errno 2] No such file or directory: 'file.gz'
      

      【讨论】:

        【解决方案4】:

        我通常设置工作目录和处理文件的方式如下:

        import os
        pwd_path= os.path.dirname(os.path.abspath(__file__))
        myfile = os.path.join(pwd_path, 'i1.gz')
        

        【讨论】:

          猜你喜欢
          • 2020-11-28
          • 1970-01-01
          • 2014-05-18
          • 1970-01-01
          • 2014-10-05
          • 1970-01-01
          • 2023-02-19
          • 2019-06-11
          • 2021-01-07
          相关资源
          最近更新 更多