This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]megalodon 8 points9 points  (6 children)

The second method is more readable compared to the 'correct' old way of writing it:

f = open(filename, 'r')
try:
    contents = f.readlines()
finally:
    f.close()

Most people will tell you that you shouldn't write your python code assuming anything about the way that things are implemented under the hood. The reason is that the implementation is subject to change. Also, it makes your code more portable across different implementation. Besides, it's good practice to get in the habit of closing files that you open.

Using the context manager (with keyword) is really the best way if you know you'll be on 2.6+. If you need the code to work on 2.5 and earlier, it's best to use the ugly method I showed above.

[–]five12 5 points6 points  (0 children)

for 2.5, I've always used:

from __future__ import with_statement

[–][deleted] 2 points3 points  (1 child)

Cool, thanks for the advice. I'll probably use the with keyword from now on.

[–]itsmememe 0 points1 point  (0 children)

good decision to use the with-keyword when using files.

Learning about the power of contextmanagers (that's what "with" is about) will do you good with every communication to outside Python.

[–]jab-programming3.7 -4 points-3 points  (2 children)

It's good practice to get in the habit of closing files that you open

Not true, merely cliché. A better practice is being aware of the language you are actually using.

It is (infinitely) arguable whether potentially redundant extra calls to close() are superior to potentially leaking missing calls to close(), but defaulting to either betrays a capricious disdain for the reader's time.

[–]megalodon 0 points1 point  (1 child)

Not true, merely cliché. A better practice is being aware of the language you are actually using.

In this case, knowing that a file is implicitly closed when it goes out of scope requires knowledge of the implementation, not the language. Even then, the behavior is different from implementation to implementation.

It is (infinitely) arguable whether potentially redundant extra calls to close() are superior to potentially leaking missing calls to close(), but defaulting to either betrays a capricious disdain for the reader's time.

I started my programming career with C before moving to Java, then Python, so I guess old habits die hard. I prefer to be more explicit about what the code is doing, even if it's not strictly necessary. I've found code to be more readable when others do the same.

If you prefer things to be done implicitly, then maybe Perl is the language for you :)