7

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 ?

Arun
  • 1,933
  • 2
  • 28
  • 46

6 Answers6

14

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)
D.L
  • 4,339
  • 5
  • 22
  • 45
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
11

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.

Arun
  • 1,933
  • 2
  • 28
  • 46
2

I've had considerable problems opening up files through Python if I don't use the absolute path or build the path using os.path. Even if the file is in the same directory as the Python file the result is the same. I used Chiheb's solution and of course it worked again (Thanks Chiheb). I do wonder if it's something going on with Python. I am using VS Code but still that shouldn't matter in my opinion if an accurate path is given.

The code for my current situation that worked using the solution above:

Sitka_highs.py

import os
import csv

absolute_path = os.path.dirname(os.path.abspath(__file__))

filename = absolute_path + '/data/sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    print(header_row)
David Buck
  • 3,752
  • 35
  • 31
  • 35
Jaclyn Horton
  • 53
  • 1
  • 7
  • I get the same. When i run the script in `VS code` it is fine (because it recognises the current working directory), but when running in a separate command prompt on `windows10`, from the `c:` drive, the code would fail unless i navigate to the same current working directory. One solution is to use the absolute path either as above or as a regular expression `r"path_to_file\file_name.csv"`. – D.L Apr 22 '21 at 08:09
1

I used below method and it worked fine for me.

FILE_PATH = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.ConfigParser()
config.readfp(open(FILE_PATH+'/conf.properties'))
Hasitha
  • 738
  • 8
  • 16
0

I don't think Python knows which dir to use... to start with the current path of the current python .py file, try:

mypath = os.path.dirname(os.path.abspath(__file__))
with open(mypath+'/zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)
Vexen Crabtree
  • 339
  • 3
  • 16
0

Say that you are on the main_folder and want to call the file first_file.py that then opens the file readme.txt:

main_folder
│
└───first_folder      
│   │   first_file.py
│   │
|   └───second_folder
│       │ readme.txt             
│
└─── ...

Python provides us with an attribute called __file__ that returns the absolute path to the file. For example, say that the content of first_file.py is just one line that prints this path: print(__file__).

Now, if we call first_file.py from main_folder we get the same result that if we call it from first_folder (note that, in Windows, the result is going to be a little bit different):

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"

And if we want to obtain the folder of first_file.py, we import the library os and we use the method os.path.dirname(__file__).

Finally, we just concatenate this folder with the one we want to access from it (second_folder) and the name of the file (readme.txt).

Simplifying, the result code is:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')

And the value of README_PATH:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"

This way, you also won't get any problems related to the Visual Studio Code debugger with the path and you'll be able to call the first_file.py from wherever you want