【问题标题】:Python error: FileNotFoundError: [Errno 2] No such file or directoryPython 错误:FileNotFoundError:[Errno 2] 没有这样的文件或目录
【发布时间】:2018-10-05 07:24:06
【问题描述】:

我正在尝试从文件夹中打开文件并读取它,但它没有找到它。我正在使用 Python3

这是我的代码:

import os
import glob

prefix_path = "C:/Users/mpotd/Documents/GitHub/Python-Sample-                
codes/Mayur_Python_code/Question/wx_data/"
target_path = open('MissingPrcpData.txt', 'w')
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if 
f.endswith('.txt')]
file_array.sort() # file is sorted list

for f_obj in range(len(file_array)):
     file = os.path.abspath(file_array[f_obj])
     join_file = os.path.join(prefix_path, file) #whole file path

for filename in file_array:
     log = open(filename, 'r')#<---- Error is here

Error: FileNotFoundError: [Errno 2] No such file or directory: 'USC00110072.txt'

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    您没有将文件的完整路径提供给open(),而只是提供它的名称 - 相对路径。

    非绝对路径指定与当前working directory 相关的位置(CWD,请参阅os.getcwd)。

    您必须os.path.join() 正确的目录路径,或os.chdir() 文件所在的目录。

    另外,请记住 os.path.abspath() 不能仅通过文件名来推断文件的完整路径。它只会在其输入前加上当前工作目录的路径,如果给定路径是相对的。

    您似乎忘记修改file_array 列表。要解决此问题,请将第一个循环更改为:

    file_array = [os.path.join(prefix_path, name) for name in file_array]
    

    让我重申一下。

    代码中的这一行:

    file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if f.endswith('.txt')]
    

    错了。它不会为您提供正确绝对路径的列表。你应该做的是:

    import os
    import glob
    
    prefix_path = ("C:/Users/mpotd/Documents/GitHub/Python-Sample-"    
                   "codes/Mayur_Python_code/Question/wx_data/")
    target_path = open('MissingPrcpData.txt', 'w')
    file_array = [f for f in os.listdir(prefix_path) if f.endswith('.txt')]
    file_array.sort() # file is sorted list
    
    file_array = [os.path.join(prefix_path, name) for name in file_array]
    
    for filename in file_array:
         log = open(filename, 'r')
    

    【讨论】:

      【解决方案2】:

      您正在使用相对路径,而您应该使用绝对路径。使用os.path 处理文件路径是个好主意。轻松修复您的代码是:

      prefix = os.path.abspath(prefix_path) 
      file_list = [os.path.join(prefix, f) for f in os.listdir(prefix) if f.endswith('.txt')]
      

      请注意,您的代码还有一些其他问题:

      1. 在 python 中你可以做for thing in things。你做了for thing in range(len(things)) 它的可读性和不必要性要低得多。

      2. 您应该在打开文件时使用上下文管理器。阅读更多here

      【讨论】:

      • 1.对于您的第一个注释:它可以帮助我获取文件夹中每个文件的位置。 2. 我使用了您的建议,但仍然显示错误。
      • 我也有同样的问题。我在 Python 中使用 ciscoconfparse 模块来读取和解析几个 cisco 配置文件。它适用于文件夹中的前 10 个配置文件。当我将其他配置添加到同一文件夹中时,它给了我 [FATAL] ciscoconfparse could not open error for the new configs I added.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多