【问题标题】:Python open() requires full pathPython open() 需要完整路径
【发布时间】:2017-06-08 04:20:16
【问题描述】:

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

【问题讨论】:

  • 什么是os.getcwd()?如果该目录与包含文件的目录不同,则相对路径不起作用。
  • 因为您在其他目录中运行 python 脚本,而 that 是您的当前目录。
  • 我在 Visual Studio 代码调试器中运行代码。
  • ...它当前的工作目录是什么?

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


【解决方案1】:

来自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()
# 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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我使用了下面的方法,对我来说效果很好。

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

      【讨论】:

        【解决方案4】:

        如果我不使用绝对路径或使用 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)
        

        【讨论】:

        • 我也一样。当我在VS code 中运行脚本时很好(因为它可以识别当前工作目录),但是当我在windows10 上的单独命令提示符下运行时,来自c: 驱动器,除非我导航到相同的当前工作目录。一种解决方案是使用上述绝对路径或正则表达式r"path_to_file\file_name.csv"
        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

          假设您在main_folder 上并想调用文件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 ?

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-05-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-05-29
            • 1970-01-01
            相关资源
            最近更新 更多