spatial
spatial

Reputation: 67

Python File Not Found Error even though file is in same directory

I'm running a python code (filename- images.py) that reads-

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

But it is showing the FileNotFoundError. My folder containing images.py looks like-

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

Upvotes: 3

Views: 11040

Answers (4)

Niv Cohen
Niv Cohen

Reputation: 1148

The way I usually set working directory and work with files is as follow:

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

Upvotes: 3

Gabio
Gabio

Reputation: 9484

The problem is that you are not running the script from within the New Folder. You can easily solve it by using the absolute path without hard-coding it:

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')

Upvotes: 4

user13177201
user13177201

Reputation:

Check the current working directory of the script by doing:

import os
os.getcwd()

Then, compare this with your i1.gz absolute path. Then you should be able to see if there are any inconsistencies.

Upvotes: 4

luipenox
luipenox

Reputation: 118

Are you run the script from the New Folder?

If you are in the folder, it should work:

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

but if you run the script from a parent folder with the folder name, it returned the error:

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'

Upvotes: 2

Related Questions