简体   繁体   中英

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.

Here's the chunk of code:

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)

Any help is appreciated. :)

Change:

for em in listing:

to:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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