The "old" version of the code inside the try / except block would be:
out = open(txtFile, 'w') for line in gzipHandler: out.write(line) out.close()
The context manager with open() ... is pretty much the same here. Python automatically closes files when their objects are garbage collected (see question 575278 ), so out will be closed when the function by which it stops executing for some reason. In addition, the OS will close the file when the Python process terminates, if for some reason it terminates catastrophically before out.close() is executed.
The context manager with open() will expand to approximately:
out = open(txtFile, 'w') try: for line in gzipHandler: out.write(line) finally: out.close()
See the βcontext managerβ link above for an explanation. So how does it work? It opens a file, executes a block of code, then explicitly closes the file. How does the "old" version that I am describing work? It opens the file, executes your code block, then implicitly closes the file when its scope is completed or when the Python process terminates.
Save, but for the "explicit" vs "implicit" parts the functionality is identical.
source share