简体   繁体   中英

issues while reading a file in python

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'

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)

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

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)
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM