FileNotFoundError: [Errno 2] No such file or directory

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

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 

回答1:

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.

Try using the exact, or absolute, path.



回答2:

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 '%s': %s" % (cwd, files)) 

That will print the current working directory along with all the files in it.

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


回答3:

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 


回答4:

try and remove the '.csv' from the name of the file, or add an extra one in the open function. worked for me.



回答5:

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

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

Lets say that the index.html file is also in the same directory "c:\index.html" when i execute the script from cmd (or shell)

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

You will get error:

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

And that because "index.html" is not in working directory which is "C:\Users\Amine>". so in order to make it work you have to change the working directory

C:\python script.py  '' 

This is why is it preferable to use absolute path.



回答6:

writing this with open('address.csv','r') as this with open('address.csv',mode='r') worked for me.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!