Python open() 需要完整路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44426569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python open() requires full path
提问by Arun
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
我正在编写一个脚本来读取一个 csv 文件。csv 文件和脚本位于同一目录中。但是当我尝试打开文件时,它给了我FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'
. 我用来读取文件的代码是
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 ?
如果我提供文件的完整路径,它将起作用。为什么open()
需要文件的完整路径?
回答by Chiheb Nexus
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.
打开(文件,模式='r',缓冲=-1,编码=无,错误=无,换行=无,closefd=真,开瓶器=无)
file 是一个类似路径的对象,给出要打开的文件的路径名(绝对或相对于当前工作目录)或要包装的文件的整数文件描述符。
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()
# Or: file_path = os.path.join(working_directory, 'my_file.py')
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__))
# Or: file_path = os.path.join(absolute_path, 'folder', 'my_file.py')
file_path = absolute_path + '/folder/my_file.py'
回答by Arun
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.
我已经确定了问题所在。我在 Visual Studio Code 调试器上运行我的代码。我打开的根目录高于我的文件级别。当我打开同一个目录时,它起作用了。
回答by Vexen Crabtree
I don't think Python knows which dir to use... to start with the current path of the current python .py file, try:
我认为 Python 不知道要使用哪个目录...以当前 python .py 文件的当前路径开始,请尝试:
mypath = os.path.dirname(os.path.abspath(__file__))
with open(mypath+'/zipcodes.csv', 'r') as zipcode_file:
reader = csv.DictReader(zipcode_file)