Reading Time: 1 minutes
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.