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.


5 thoughts on “The with statement”

  1. 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’).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s