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.

Leave a Comment