Sunday, March 3, 2024

The with assertion – Yasoob Khalid


So the possibilities are that you just already know in regards to the with assertion however a few of us have no idea about it. Lets face the fact the with assertion saves us a whole lot of time and reduces our code base. Simply think about you might be opening a file width python after which saving one thing to it. You’ll usually do:

file = open('file.txt','w')
file.write("freepythontips.wordpress.com")
file.shut()

However what if an exception happens whereas writing to file ? then the file received’t be closed correctly. I understand how a lot bother it might probably trigger. It as soon as occurred with me that i used to be operating an online scrapper and it was operating for previous three hours after which unexpectedly an exception occured and my entire csv file acquired corrupted and that i needed to run the scrapper once more.

So lets come to the purpose. What technique are you able to undertake to forestall such catastrophe. Clearly you can’t stop the exception when it’s sudden however you’ll be able to take some precautions. Firstly you’ll be able to wrap up your code in a try-except clause or higher but you need to use a with assertion. Let’s first speak about try-except clause. You’ll usually do one thing like this:

attempt:
    file = open('file.txt','w')
    file.write(information)
besides:
    # do one thing in case of an exception
lastly:
    # right here comes the trick. The lastly clause will get 
    # executed even when an exception occured in attempt 
    # or besides clause. now we are able to safely shut this
    # file.
    file.shut()

Now lets discuss in regards to the with assertion. Whereas utilizing a with assertion you’d usually do:

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

Okay so right here whereas utilizing the with assertion we shouldn’t have to shut the file explicitly. It’s robotically closed after the info is written to the file.

Do share your views about this submit under within the feedback.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles