On 02/16/2016 11:04 PM, jf...@ms4.hinet.net wrote: > Thanks for these detailed explanation. Both statements will close file > automatically sooner or later and, when considering the exceptions, "with" is > better. Hope my understanding is right. > > But, just curious, how do you know the "for" will do it? I can't find any > document about it from every sources I know. Very depressed:-( > > --Jach >
First-- IMO, don't depend on it. Instead, use something like: with open('foo.txt') as f: for line in f: pass # do something here It's one extra indent and one extra line, but it's cleaner. To answer your question, technically, it might not-- it really depends upon your implementation of Python. It just so happens that the most popular version of Python (CPython, the reference implementation) will garbage collect the file object right away. HOWEVER. The reason the "for" will PROBABLY result in file closure is because as soon as the for loop exits, there is no reason to hold onto the object returned by "open", so it is disposed. When file objects are disposed, they are closed. IMO, don't depend on this behaviour; it's bad form. -- https://mail.python.org/mailman/listinfo/python-list