我正在尝试打开一个 CSV 文件,但由于某种原因 python 无法找到它.
I am trying to open a CSV file but for some reason python cannot locate it.
这是我的代码(这只是一个简单的代码,但我无法解决问题):
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
当你打开一个名为 address.csv
的文件时,你是在告诉 open()
您的文件在当前工作目录中的功能.这称为相对路径.
When you open a file with the name address.csv
, you are telling the open()
function that your file is in the current working directory. This is called a relative path.
为了让您了解这意味着什么,请将其添加到您的代码中:
To give you an idea of what that means, add this to your code:
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))
这将打印当前工作目录以及其中的所有文件.
That will print the current working directory along with all the files in it.
告诉 open()
函数的另一种方法是使用绝对路径,例如:
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")
这篇关于FileNotFoundError: [Errno 2] 没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!