简体   繁体   English

在python中读取文件时出现的问题

[英]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:我正在努力在 python 中读取文件,py 文件和 CSV 文件在同一个文件夹中,但是 VSCode 出错并且找不到文件:

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'发生异常:FileNotFoundError [Errno 2] 没有这样的文件或目录:'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.如果您通过 VS 代码运行 python 脚本,它可能正在使用它可能是您在左侧打开的目录。

So either run the python using the correct working directory or use an absolute path like this:因此,要么使用正确的工作目录运行 python,要么使用这样的绝对路径:

import csv

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

Are you using spyder?你在用spyder吗? If so, please check if the current working path is the path your py file locates.如果是这样,请检查当前工作路径是否是您的 py 文件所在的路径。

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在这种情况下,您的 file.csv 应该位于您的 python 脚本(当前工作文件夹)所在的文件夹中,或者,您可以放置​​绝对路径而不是 'file.csv'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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