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'
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())