Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading