FileNotFoundError: [ Errno 2]没有这样的文件或目录

我试图打开一个 CSV 文件,但由于某些原因,python 无法找到它。

Here is my code (it's just a simple code but I cannot solve the problem):

import csv


with open('address.csv','r') as f:
reader = csv.reader(f)
for row in reader:
print row
1275200 次浏览

You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.

尝试使用精确的或绝对的路径。

当你打开一个名为 address.csv的文件时,你告诉 open()函数你的文件在当前工作目录中。这叫做相对路径。

为了让您了解这意味着什么,请将以下内容添加到代码中:

import os


cwd = os.getcwd()  # Get the current working directory (cwd)
files = os.listdir(cwd)  # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))

这将打印当前的工作目录和其中的所有文件。

Another way to tell the open() function where your file is located is by using an absolute path, e.g.:

f = open("/Users/foo/address.csv")

Use the exact path.

import csv




with open('C:\\path\\address.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)

Lets say we have a script in "c:\script.py" that contain :

result = open("index.html","r")
print(result.read())

假设 index.html 文件也在同一目录“ c: index.html”中 当我从 cmd (或 shell)执行脚本时

C:\Users\Amine>python c:\script.py

你会得到错误:

FileNotFoundError: [Errno 2] No such file or directory: 'index.html'

这是因为“ index.html”的工作目录不是“ C: Users Amine >”。所以为了让它工作,你必须改变工作目录

C:\python script.py


'<html><head></head><body></body></html>'

这就是为什么最好使用绝对路径。

对于那些尽管传递了绝对路径但仍然出错的人,应该检查 file 是否有有效的名称。对我来说,我试图创建一个文件名中包含’/’的文件。只要删除“/”,就能创建文件。

with open(fpath, 'rb') as myfile:
fstr = myfile.read()

I encounter this error because 文件是空的. This answer may not be a correct answer for this question but hopefully it can give some of you a hint.