IOError: [Errno 2] No such file or directory

Question:

im having problems trying to run an iteration over many files in a folder, the files exist, if I print file from files I can see their names…
Im quite new to programming, could you please give me a hand? kind regards!

import os
for path, dirs, files in os.walk('FDFFDF'):
    for file in files:
        print file
        fdf = open(file, "r")
IOError: [Errno 2] No such file or directory: 'FDF_20110612_140613_...........txt'
Asked By: Patowski

||

Answers:

You need to prefix each file name with path before you open the file.

See the documentation for os.walk.

import os
for path, dirs, files in os.walk('FDFFDF'):
    for file in files:
        print file
        filepath = os.path.join(path, file)
        print filepath
        fdf = open(filepath, "r")
Answered By: Jonathan Leffler

Try this:

import os

for path, dirs, files in os.walk('FDFFDF'):
    for file in files:
        print file
        with open(os.path.join(path, file)) as fdf:
            # code goes here.
Answered By: Mike DeSimone
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.