繁体   English   中英

Python 错误:FileNotFoundError: [Errno 2] 没有那个文件或目录

[英]Python error: FileNotFoundError: [Errno 2] No such file or directory

我试图从文件夹中打开文件并读取它,但它没有找到它。 我正在使用 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() ,只是它的名称 - 相对路径。

非绝对路径指定与当前工作目录相关的位置(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')

您正在使用相对路径,而您应该使用绝对路径。 使用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 thingsfor thing in things for thing in range(len(things))for thing in range(len(things))所做for thing in range(len(things))可读性和不必要性要低得多。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM