Python open() requires full path

不想你离开。 提交于 2019-12-08 11:37:47

问题


I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)

If I give the full path to the file, it will work. Why open() requires full path of the file ?


回答1:


From the documentation:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

So, if the file that you want open isn't in the current folder of the running script, you can use an absolute path, or getting the working directory or/and absolute path by using:

import os
# Look to the path of your current working directory
working_directory = os.getcwd()
file_path = working_directory + 'my_file.py'

Or, you can retrieve your absolute path while running your script, using:

import os
# Look for your absolute directory path
absolute_path = os.path.dirname(os.path.abspath(__file__))
file_path = absolute_path + '/folder/my_file.py'



回答2:


I have identified the problem. I was running my code on Visual Studio Code debugger. The root directory I have opened was above the level of my file. When I opened the same directory, it worked.




回答3:


I don't think Python knows which dir to use... to start with the current path of the current python .py file, try:

mypath = os.path.dirname(os.path.abspath(__file__))
with open(mypath+'/zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)


来源:https://stackoverflow.com/questions/44426569/python-open-requires-full-path

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