I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'
. The code I used to read the file is
with open('zipcodes.csv', 'r') as zipcode_file:
reader = csv.DictReader(zipcode_file)
If I give the full path to the file, it will work. Why open()
requires full path of the file ?
Python open() Function The open() function opens a file, and returns it as a file object. Read more about file handling in our chapters about File Handling.
To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.
However, once Python exits from the “with” block, the file is automatically closed. Trying to read from f after we have exited from the “with” block will result in the same ValueError exception that we saw above. Thus, by using “with”, you avoid the need to explicitly close files.
From the documentation:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.
So, if the file that you want open isn't in the current folder of the running script, you can use an absolute path, or getting the working directory or/and absolute path by using:
import os
# Look to the path of your current working directory
working_directory = os.getcwd()
# Or: file_path = os.path.join(working_directory, 'my_file.py')
file_path = working_directory + 'my_file.py'
Or, you can retrieve your absolute path while running your script, using:
import os
# Look for your absolute directory path
absolute_path = os.path.dirname(os.path.abspath(__file__))
# Or: file_path = os.path.join(absolute_path, 'folder', 'my_file.py')
file_path = absolute_path + '/folder/my_file.py'
If you want to be operating system agnostic, then you can use:
file_path = os.path.join(absolute_path, folder, my_file.py)
I have identified the problem. I was running my code on Visual Studio Code debugger. The root directory I have opened was above the level of my file. When I opened the same directory, it worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With