2

I understand that the with block automatically calls close() after you exit the block, and that it is often used to make sure one doesn't forget to close a file.

It seems that there is no technical difference between

with open(file, 'r+') as f:
    do_things(f)

and

f = open(file, 'r+')
do_things(f)
f.close()

Is one way more Pythonic than the other? Which should I use in my code?

rivermont
  • 223
  • 2
  • 12
  • 3
    There is a HUGE technical difference between the two! The `with` version ensures that `close()` gets called, even if `do_things()` raises an exception. You'd need to add a `try` and a `finally` to the other version to match this behavior. – jasonharper May 28 '17 at 02:16
  • 1
    FWIW, I don't think this question is an duplicate of 3012488. The topics do overlap but the other question is very broad and doesn't specifically address which approach is more Pythonic for closing files. – Raymond Hettinger May 28 '17 at 21:33

1 Answers1

3

Is one way more Pythonic than the other?

Yes, the with-statement form is preferred, it encapsulates the file administration logic into a single line of code. The improves the ratio of business-logic to admin-logic, making the program easier to read and reason about.

Per PEP 343, the intended purpose of the with-statement is:

This PEP adds a new statement "with" to the Python language to make
it possible to factor out standard uses of try/finally statements.
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485