The with statement

So the chances are that you already know about the with statement but some of us do not know about it. Lets face the reality the with statement saves us a lot of time and reduces our code base. Just imagine you are opening a file width python and then saving something to it. You would normally do:

file = open('file.txt','w')

But what if an exception occurs while writing to file ? then the file won’t be closed properly. I know how much trouble it can cause. It once happened with me that i was running a web scrapper and it was running for past three hours and then unexpectedly an exception occured and my whole csv file got corrupted and i had to run the scrapper again.

So lets come to the point. What method can you adopt to prevent such disaster. Obviously you can not prevent the exception when it is unexpected but you can take some precautions. Firstly you can wrap up your code in a try-except clause or better yet you can use a with statement. Let’s first talk about try-except clause. You would normally do something like this:

    file = open('file.txt','w')
    # do something in case of an exception
    # here comes the trick. The finally clause gets 
    # executed even if an exception occured in try 
    # or except clause. now we can safely close this
    # file.

Now lets talk about the with statement. While using a with statement you would normally do:

with open('file.txt','w') as file:

Okay so here while using the with statement we do not have to close the file explicitly. It is automatically closed after the data is written to the file.

Do share your views about this post below in the comments.



If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I send it out every other month. It contains new stuff that I make, links I find interesting on the web, and occasional discount coupons for my book. Join the 5000+ other people who receive my newsletter:

I send out the newsletter once every other month. No spam, I promise + you can unsubscribe at anytime

✍️ Comments


Good post, but a couple of minor nitpicks: According to PEP8, there should be a space in open(‘file.txt’,‘w’) . file is also not a good variable name, since it will (at least in Python 2) overshadow a built-in and therefore confuse people. Additionally, open(‘file.txt’, ‘w’) is virtually never the right thing to do since it involves a lot of guessing and can have crazy semantics on platforms. In >99% of the cases, you either want to use or open(‘file’, ‘wb’).

In reply to Philipp

Philipp thanx for your response i have made those edits.

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊