I have a python script that has a line with open('gg.csv') as csv_file:, and I have a csv file called gg.csv in the exact same directory as the python file, but when I run the script I am getting FileNotFoundError: [Errno 2] No such file or directory: 'gg.csv' - does anyone know of the solution?
4 Answers
This is probably beacuse you run the script from different directoy.
For instance, if I have the following script at my Desktop:
import os
print(os.getcwd())
running the script from the Desktop I get:
~/Desktop » py3 SO.py Sriker@Sriker-MBP
/Users/Sriker/Desktop
While from different directory I get:
~ » py3 Desktop/SO.py Sriker@Sriker-MBP
/Users/Sriker
So you either run the script from the right directory, or build the path to gg.csv properly before trying to open it.
Comments
tl;dr: You are running your script in another directory.
You are running it in another directory other than the main one. Basically, "gg.csv" in python has a relative path. For example, if I am in my home directory, (in Linux) this should correspond to the path of:
/home/<whatever username>/gg.csv
But say you are in your Desktop directory, in Linux, python interprets that as:
/home/<whatever username>/Desktop/gg.csv
Because you are running it in a different directory, Python thinks you are corresponding to the gg.csv there, not the gg.csv with the directory that has the script.
Thus, run it in the correct directory or set a absolute path that always links to the correct directory and path.
import osand thenprint(os.getcwd())