FileNotFoundError,Python [英] FileNotFoundError, Python

查看:57
本文介绍了FileNotFoundError,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to open the files in my folder but it came out with this error:

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

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

I had double check the file name and the directory/path written in the code but the problem still there.

代码如下:

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)

感谢任何帮助.:)

推荐答案

更改:

for em in listing:

到:

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

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

This should solve your problem. The return from os.listdir() is a list of relative paths. You need to make them absolute paths if you're not invoking the app in the path directory. Otherwise they are not found, as you've seen.

这篇关于FileNotFoundError,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆