Python错误:FileNotFoundError:[Errno 2]没有这样的文件或目录。

6

我正在尝试从文件夹中打开文件并读取它,但是找不到它。我正在使用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

错误:FileNotFoundError:[Errno 2]没有那个文件或目录:'USC00110072.txt'
2个回答

11

open()函数要求提供文件的完整路径,而不仅仅是文件名,即相对路径。

非绝对路径指定与当前工作目录(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. 当打开文件时,应该使用上下文管理器。点击此处查看更多信息。


  1. 对于你的第一个笔记:它帮助我获取文件夹中每个文件的位置。
  2. 我已经使用了你的建议,但仍然出现错误。
- Mayur Potdar
我也遇到了同样的问题。我正在使用Python中的ciscoconfparse模块来读取和解析多个Cisco配置文件。它可以正常地处理文件夹中前10个配置文件。但是,当我向同一文件夹添加其他配置文件时,它会对我添加的新配置文件出现[FATAL] ciscoconfparse无法打开的错误。 - CBLT

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