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

13 浏览
0 Comments

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

我正在尝试从文件夹中打开并读取文件,但无法定位它。我正在使用Python3。以下是我的代码:\n

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() # 文件已排序列表
for f_obj in range(len(file_array)):
    file = os.path.abspath(file_array[f_obj])
    join_file = os.path.join(prefix_path, file) # 整个文件路径
for filename in file_array:
    log = open(filename, 'r')#<---- 错误出现在这里

\n错误信息:FileNotFoundError: [Errno 2] No such file or directory: \'USC00110072.txt\'

0
0 Comments

Python错误:FileNotFoundError: [Errno 2] No such file or directory

问题原因:

您在使用相对路径时应该使用绝对路径。最好使用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. 我已经使用了您的建议,但仍然显示错误。

我遇到了相同的问题。我在Python中使用ciscoconfparse模块来读取和解析多个Cisco配置文件。它可以正常处理文件夹中前10个配置文件。但是,当我将其他配置文件添加到同一文件夹中时,它会给我新添加的配置文件显示[FATAL] ciscoconfparse无法打开的错误提示。

0
0 Comments

Python错误:FileNotFoundError: [Errno 2] No such file or directory(文件未找到错误)出现的原因是路径错误,没有给出文件的完整路径,只给出了相对路径。非绝对路径是指相对于当前工作目录(CWD)的位置。

解决方法有两种:

1. 使用os.path.join()将正确的目录路径连接到文件名上。

2. 使用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_array = [os.path.join(prefix_path, name) for name in file_array]

for filename in file_array:

log = open(filename, 'r')

0