Python open()需要完整路径

时间:2017-06-08 04:20:16

标签: python file visual-studio-code python-3.4

我正在编写一个脚本来读取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)

如果我提供文件的完整路径,它将起作用。为什么open()需要文件的完整路径?

5 个答案:

答案 0 :(得分:4)

来自documentation

  

打开(文件,模式=' r',缓冲= -1,编码=无,错误=无,   newline = None,closefd = True,opener = None)

     

file是一个类似路径的对象,它给出了路径名(绝对或相对的)   到当前工作目录)要打开的文件或   要包装的文件的整数文件描述符。

因此,如果您要打开的文件不在正在运行的脚本的当前文件夹中,则可以使用绝对路径,或使用以下方式获取工作目录或/和绝对路径:

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

或者,您可以在运行脚本时检索绝对路径,使用:

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'

答案 1 :(得分:2)

我已经确定了问题所在。我在Visual Studio Code调试器上运行我的代码。我打开的根目录高于我的文件级别。当我打开同一个目录时,它有效。

答案 2 :(得分:2)

如果我不使用绝对路径或使用os.path构建路径,则在通过Python打开文件时会遇到很多问题。即使文件与Python文件位于同一目录中,结果也相同。我使用了Chiheb的解决方案,它当然又可以工作了(谢谢Chiheb)。我确实想知道这是否与Python有关。我正在使用VS Code,但我认为如果给出了正确的路径也没关系。

使用上述解决方案的当前情况代码:

Sitka_highs.py

import os
import csv

absolute_path = os.path.dirname(os.path.abspath(__file__))

filename = absolute_path + '/data/sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    print(header_row)

答案 3 :(得分:0)

我不认为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)

答案 4 :(得分:0)

我使用以下方法,对我来说效果很好。

FILE_PATH = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.ConfigParser()
config.readfp(open(FILE_PATH+'/conf.properties'))