gonzalloe
gonzalloe

Reputation: 313

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. :)

Upvotes: 0

Views: 1324

Answers (1)

GaryMBloom
GaryMBloom

Reputation: 5682

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.

Upvotes: 2

Related Questions