【问题标题】:FileNotFoundError, PythonFileNotFoundError, Python
【发布时间】:2017-12-10 03:05:21
【问题描述】:

我正在尝试打开文件夹中的文件,但出现以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'TRAIN_00000.eml'

我仔细检查了代码中写入的文件名和目录/路径,但问题仍然存在。

这是代码块:

import os

path = "C:\\Users\\...\\TRAINING"
listing = os.listdir(path)


for em in listing:
    file = open(em, 'rb')
    e_content = file.read()
    file.close()

print (e_content)

感谢任何帮助。 :)

【问题讨论】:

  • os.listdir() 只返回文件名,你必须 os.path.join() 他们和路径。

标签: python python-3.x path file-not-found


【解决方案1】:

变化:

for em in listing:

到:

for em in listing:
    em = os.path.join(path, em) # this is what you need to add

这应该可以解决您的问题。 os.listdir() 的返回是一个相对路径列表。如果您不在 path 目录中调用应用程序,则需要将它们设为绝对路径。否则,如您所见,它们不会被找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多