Search code examples
pythonioerror

IOError: [Errno 2] No such file or directory


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('FDF\FDF'):
    for file in files:
        print file
        fdf = open(file, "r")
IOError: [Errno 2] No such file or directory: 'FDF_20110612_140613_...........txt'

Solution

  • 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('FDF\FDF'):
        for file in files:
            print file
            filepath = os.path.join(path, file)
            print filepath
            fdf = open(filepath, "r")