So the probabilities are that you simply 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’d 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 gained’t be closed correctly. I understand how a lot hassle 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 complete csv file received corrupted and that i needed to run the scrapper once more.
So lets come to the purpose. What methodology are you able to undertake to stop such catastrophe. Clearly you can’t forestall 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 should utilize a with assertion. Let’s first discuss try-except clause. You’d usually do one thing like this:
strive: 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 strive # 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’ll usually do:
with open('file.txt','w') as file: file.write(information)
Okay so right here whereas utilizing the with assertion we do not need to shut the file explicitly. It’s mechanically closed after the information is written to the file.
Do share your views about this put up beneath within the feedback.