Search code examples
pythonioerror

Opening .out files in Python


Am I right in thinking Python cannot open and read from .out files?

My application currently spits out a bunch of .out files that would be read manually for logging purposes, I'm building a Python script to automate this.

When the script gets to the following

for file in os.listdir(DIR_NAME):
    if (file.endswith('.out')):
        open(file)

The script blows up with the following error "IOError : No such file or directory: 'Filename.out' "

I've a similar function with the above code and works fine, only it reads .err files. Printing out DIR_NAME before the above code also shows the correct directory is being pointed to.


Solution

  • os.listdir() returns only filenames, not full paths. Use os.path.join() to create a full path:

    for file in os.listdir(DIR_NAME):
        if (file.endswith('.out')):
            open(os.path.join(DIR_NAME, file))