Python @ DjangoSpin

Python: Using the with keyword

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Using with keyword in Python

Using with keyword in Python

The with keyword automatically shuts down resources as soon as the code block following it is executed. It is considered good practice while dealing with connections, file objects etc. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally clauses.

>>> with open('fileToBeReadFrom.txt', 'r') as fH:
       contents = fH.read()
>>> fH.closed
True

If you wish to know more about how the with statement works, click here.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply