Python中的open()函数需要完整路径。

7

我正在编写一个脚本来读取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()需要文件的完整路径?


2
os.getcwd()是什么?如果它不是包含文件的同一目录,那么相对路径就无法工作。 - Dan D.
3
因为您在某个其他目录中运行Python脚本,而那个目录是您当前的目录。 - John Gordon
我正在使用Visual Studio Code调试器运行代码。 - Arun
它的当前工作目录是什么? - tdelaney
6个回答

14

根据文档:

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

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

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

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'

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

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'

如果您想成为操作系统通用的话,那么您可以使用:

file_path = os.path.join(absolute_path, folder, my_file.py)

11

我已经找到了问题所在。我在 Visual Studio Code 的调试器上运行我的代码时,打开的根目录比我文件所在的目录高了一级。当我打开相同的目录时,它可以正常工作。


2
我曾经在使用Python打开文件时遇到了很多问题,如果我不使用绝对路径或者使用os.path构建路径,即使文件与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)

我遇到了同样的问题。当我在VS Code中运行脚本时,一切正常(因为它识别当前工作目录),但是当我在Windows10上从c:驱动器的单独命令提示符中运行时,除非我导航到相同的当前工作目录,否则代码将失败。一个解决方案是使用绝对路径,如上所述或作为正则表达式r"path_to_file\file_name.csv" - D.L

1

我使用了以下方法,它对我很有效。

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

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)

0
假设您在主文件夹中,想要调用文件first_file.py,然后打开文件readme.txt
main_folder
│
└───first_folder      
│   │   first_file.py
│   │
|   └───second_folder
│       │ readme.txt             
│
└─── ...

Python 提供了一个名为 __file__ 的属性,它返回文件的绝对路径。例如,假设 first_file.py 的内容只有一行代码,用于打印此路径:print(__file__)

现在,如果我们从 main_folder 调用 first_file.py,我们将得到与从 first_folder 调用它相同的结果(请注意,在 Windows 中,结果会略有不同):

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"

如果我们想要获取first_file.py的文件夹,我们需要导入库os并使用方法os.path.dirname(__file__)

最后,我们只需将此文件夹与我们想要从中访问的文件夹(second_folder)和文件名(readme.txt)连接起来即可。

简化后,结果代码如下:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')

而README_PATH的值为:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"

这样做,您也不会遇到与 Visual Studio Code 调试器路径相关的任何问题,并且您将能够从任何地方调用 first_file.py


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接