user11508332
user11508332

Reputation: 667

cannot read csv file in python

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?

Upvotes: 0

Views: 242

Answers (4)

new Q Open Wid
new Q Open Wid

Reputation: 2283

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.

Upvotes: 0

Debi
Debi

Reputation: 16

with open(r'gg.csv') as csv_file:

this may work otherwise use

df=pd.read_csv("gg.csv")

if the csv is in row and column format.

Upvotes: 0

Sai Prashanth
Sai Prashanth

Reputation: 196

Which os are you using?. Try with providing full url to your file and see if it works

If you are using Windows, try renaming

open('gg.csv')

to

open('\gg.csv')

Upvotes: 0

David
David

Reputation: 8298

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.

Upvotes: 2

Related Questions