2

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'
2
  • 1
    is some.log in the working directory? Tryopen( os.path.join(location, 'some_log')) Commented Nov 20, 2015 at 17:06
  • works like a charm - thanks! Commented Nov 20, 2015 at 17:09

1 Answer 1

6

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.