Open a .log extension file in Python

robinhood91 picture robinhood91 · Nov 20, 2015 · Viewed 12.6k times · Source

I'm trying to open a .log extension file in Python but I keep encountering an IOError. I'm wondering if this has to do with the extension because clearly, the only way to get into that loop was if 'some.log' existed in the directory.

location = '/Users/username/Downloads'

for filename in os.listdir(location):
    if filename == 'some.log':
       f  = open('some.log', "r")
       print (f.read())

Traceback:

f  = open('some.log', "r")
IOError: [Errno 2] No such file or directory: 'some.log'

Answer

Wondercricket picture Wondercricket · Nov 20, 2015

When attempting to open a file in a different directory, you need to supply the absolute file path. Otherwise it attempts to open a file in the current directory.

You can use os.path.join to concatenate the location and filename

import os

location = '/Users/username/Downloads'
for filename in os.listdir(location):
    if filename == 'some.log':
       f  = open(os.path.join(location, 'some.log'), "r")
       print (f.read())