cool guy
cool guy

Reputation: 23

Using with ... as statements vs simply declaring variables

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.

Upvotes: 2

Views: 159

Answers (3)

A. Herlas
A. Herlas

Reputation: 183

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.

Upvotes: 0

MatsLindh
MatsLindh

Reputation: 52802

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.

Upvotes: 5

Alexander
Alexander

Reputation: 63227

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.

Upvotes: 2

Related Questions