Just curious, is there any difference between the two ways below for file reading? Eso. in terms of memory usage.
with open(...) as f:
for line in f:
<do something with line>
f=open(...)
for line in f:
#process line
Also I know for gzip file, the first one with ‘with’ cannot work.
thx
No, they’re quite identical, except that the first one makes sure the file is closed. The second does not. In other words, within the body of the
withstatement,fis just a file object which is exactly equivalent to thefobject you get after just callingopenin the second code snippet.As you might know (and if you do not, make sure to read the informative doc), the
withstatement accepts an object that implements the context manager interface and invokes the__enter__method of the object on entry, and its__exit__method when it’s done (whether naturally, or with an exception.Looking at the source code (
Objects/fileobject.c), here’s the mapping (part of thefile_methodsstructure) for these special methods:So, the file object’s
__enter__method just returns the file object itself:While its
__exit__method closes the file: