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

May*_*dar 2 python file python-3.x

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

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

Bła*_*lik 5

您没有将文件的完整路径提供给open(),只是文件名。

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

从您的代码中,我可以推断出您忘记了修改file_array列表。要解决此问题,请将第一个循环更改为此:

file_array = [os.path.join(prefix_path, name) for name in file_array]
Run Code Online (Sandbox Code Playgroud)

另外,请记住,os.path.abspath()仅凭文件名无法推断出文件的完整路径。


让我重申一下。

您代码中的这一行:

file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if f.endswith('.txt')]
Run Code Online (Sandbox Code Playgroud)

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

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')
Run Code Online (Sandbox Code Playgroud)