即使文件位于同一目录中,也找不到Python文件错误

问题描述 投票:1回答:3

我正在运行一个读取以下内容的python代码(文件名-images.py)-

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

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

New Folder/
   images.py
   i1.gz
   (...Some other files...)
python file-not-found
3个回答
0
投票

您是否从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'

0
投票

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

import os
os.getcwd()

然后,将其与您的i1.gz 绝对路径进行比较。然后,您应该可以查看是否存在任何不一致之处。


0
投票

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

from os import path
path = path.abspath(__file__) # full path of your script
dir_path = path.dirname(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')

© www.soinside.com 2019 - 2024. All rights reserved.