-3

I'm struggling with reading a file in python, the py file and CSV file are in the same folder but the VSCode makes an error and can't find the file:

import csv

 with open('file.csv','r') as f:
 reader = reader(f)
  ...

how can I fix this?? and the error is:

Exception has occurred: FileNotFoundError [Errno 2] No such file or directory: 'file.csv'

  • 2
    The file you are trying to access is not where you expect it to be. How are you calling your script? – BoboDarph Feb 13 '19 at 12:43
  • You might not be specifying the correct path in `open`. This might help: https://stackoverflow.com/a/44426646 – JoshG Feb 13 '19 at 12:43
  • 2
    `FileNotFoundError` should be usually relatively straight forward. You can generally take it for face value and just ask why: Typo? Not were you think you are for relative path anchor? – Ondrej K. Feb 13 '19 at 12:43
  • just try to open using absolute path. – Anonymous Feb 13 '19 at 12:48

4 Answers4

1

If you run:

import os
os.getcwd()

You'll find out your current working directory which I assume is not the one you were expecting. If you're running the python script through VS code it could be using it could be the directory which you have open on the left hand side.

So either run the python using the correct working directory or use an absolute path like this:

import csv

 with open('pathname/file.csv','r') as f:
     reader = reader(f)
Tom Dee
  • 2,516
  • 4
  • 17
  • 25
0

Are you using spyder? If so, please check if the current working path is the path your py file locates.

  • Hi, welcome to stackoverflow. Maybe you want to take a look at [this](https://stackoverflow.com/help/how-to-answer) ;-) – Joey Feb 13 '19 at 12:54
0

There might be an issue with your relative path settings.

Try this:

import os
import csv

dir = os.path.dirname(__file__)
filename = os.path.join(dir, 'file.csv')

with open(filename,'r') as f:
 reader = reader(f)
0
import csv

with open('file.csv','r') as f:
    reader = csv.reader(f)

in this case your file.csv should be in folder where is your python script (current working folder) or, instead of 'file.csv' you can put absolute path

ncica
  • 7,015
  • 1
  • 15
  • 37