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

Krushnakant Bhattad :

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...)
Gabip :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407875&siteId=1