Why is `with open()` better for opening files in Python?

There's no other advantage of with: ensuring cleanup is the only thing it's for.

You need a scoped block anyway in order to close the file in the event of an exception:

writefile = random.choice([True, False])
f = open(filename) if writefile else None
try:
    # some code or other
finally:
    if writefile:
        f.close()

So, the thing you describe as a disadvantage of with is really a disadvantage of correct code (in the case where cleanup is required), no matter how you write it.


We want that guarantee that some cleanup/finalization takes place. That is the use of with.

Yes, most commonly, we would like to close a file, but you could come up with other examples.

PEP 343 has a non-file example:

A template for ensuring that a lock, acquired at the start of a block, is released when the block is left:

@contextmanager
def locked(lock):
    lock.acquire()
    try:
        yield
    finally:
        lock.release()

Used as follows:

with locked(myLock):
    # Code here executes with myLock held.  The lock is
    # guaranteed to be released when the block is left (even
    # if via return or by an uncaught exception).

besides not having to explicitly close the file, are there other reasons to use the with syntax for handling files

I think the main reason for using ContextManager during file open is idea that this file will be open in any case whether everything is ok or any exception is raised.

it Is analog for following statement

f = open(filename, 'w')
try:
    pass
finally:
    f.close()