Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python open() requires full path

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 ?

like image 721
Arun Avatar asked Jun 08 '17 04:06

Arun


People also ask

What does open () do in Python?

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.

How do you give a full path in Python?

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.

Do you need to close file when using with open Python?

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.


2 Answers

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)
like image 132
Chiheb Nexus Avatar answered Oct 16 '22 15:10

Chiheb Nexus


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.

like image 45
Arun Avatar answered Oct 16 '22 16:10

Arun