Using with … as statements vs simply declaring variables

Question:

I just started learning python via Jupyter.

What’s the difference between code 1 and code 2?

  1. Using with:

    with open('myfile.txt') as new_file:
        contents = new_file.read()
    
  2. Without using with:

    new_file = open('myfile.txt')
    contents = new_file.read()
    

Can I use code 2 always? It’s more straightforward than code 1.

Asked By: cool guy

||

Answers:

Ironically, in your second snippet you forgot to close(new_file), which is exactly why with exists.

It’s really no more straightforward, but that doesn’t even matter, because it’s wrong.

Answered By: Alexander

In the first case you’re using what’s called a context manager – i.e. when the with block is finished, the file will also be closed afterwards (since it’s no longer needed after the with block has finished executing).

This means that the two pieces of code doesn’t do the same – instead, you’d have to also remember to close the file after reading it in the latter case:

new_file = open('myfile.txt')
contents = new_file.read()
new_file.close()

In addition, an exception might happen which the code that wraps your code uses, so in that case you have to make sure to close it even if an exception occurs:

new_file = open('myfile.txt')

try:
    contents = new_file.read()
finally:
    new_file.close()

And instead of doing this manually, you can let Python handle it automagically by you as the file handle itself can be context manager:

with open('myfile.txt') as new_file:
    contents = new_file.read()

No more manually thinking about when to close the file and how to handle any potential alternative flows.

Answered By: MatsLindh

For the first case: You don’t need to explicitly call the close() method. It is done internally.

As for the second you should explicitly call the close() method.

Answered By: A. Herlas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.