1
\$\begingroup\$

Everything that I've read online says that the best way to open a file in python is:

with open('<filename>') as f:
    for line in f.read().splitlines():
        print line

That way you don't have to worry about forgetting to close the file. But I put this in an assignment in my python class and my professor marked points off saying that it was "VB style" (I have no idea what that means, Visual Basic style?) and that from now on I should open a file this way in python:

f=open('<filename>')
for line in f.read().splitlines():
        print line
f.close()

That seems messy to me and like you would run the risk of forgetting to close one of your files, but then again I'm just a student. What's the best way to open a file in Python?

\$\endgroup\$
3
  • 6
    \$\begingroup\$ Oh, and to your question. You are right. Your professor is wrong. \$\endgroup\$ Mar 26 '17 at 2:42
  • 4
    \$\begingroup\$ It's sad to see that someone teaching Python doesn't understand the value of Pythonic constructs. \$\endgroup\$ Mar 26 '17 at 8:45
  • \$\begingroup\$ Personally, I think unsuitable questions from new users should be placed on hold or closed, but not repeatedly downvoted by more experienced users. Punishment for first attempts discourages new additions to the community. \$\endgroup\$ Mar 26 '17 at 18:25
4
\$\begingroup\$

Rather than using f.read().splitlines(), you can iterate the file object allowing you to use:

with open('<filename>') as f:
    for line in f:
        print line

Using with is better for various reasons, you don't have to remember to close the file, as you said in the question. It also closes the file, even if an error happened, which the second code doesn't. Take the following:

FILE_NAME = 'test_file.txt'
with open(FILE_NAME, 'w') as f:
    f.write('Hello World')

f = open(FILE_NAME)
try:
    with f:
        raise Exception()
        print f.read()
except Exception:
    try:
        print f.read()
    except ValueError:
        print 'I/O operation on closed file'

f = open(FILE_NAME)
try:
    raise Exception()
    print f.read()
except Exception:
    try:
        print f.read()
    except ValueError:
        print 'I/O operation on closed file'


f = open(FILE_NAME)
try:
    try:
        raise Exception()
        print f.read()
    finally:
        f.close()
except Exception:
    try:
        print f.read()
    except ValueError:
        print 'I/O operation on closed file'

This outputs two I/O error messages and one 'Hello World'. The single hello world is using the second way, without a finally to close the file. And so if you did want to use the second method, then you'd want to use something like:

try:
    f=open('<filename>')
    for line in f:
        print line
finally:
    f.close()

And, we all know which is easier to read an write. For more information about the with statement you can look into PEP 343, which explains why it was added to Python.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.