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

2024-04-21

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


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

非绝对路径指定相对于当前的位置工作目录 https://en.wikipedia.org/wiki/Working_directory(CWD,参见os.getcwd https://docs.python.org/3/library/os.html#os.getcwd).

你必须要么os.path.join()正确的目录路径,或者os.chdir()到文件所在的目录。

另外,请记住os.path.abspath() https://docs.python.org/3/library/os.path.html#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')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python错误:FileNotFoundError:[Errno 2]没有这样的文件或目录[重复] 的相关文章

随机推荐