Will file be closed automatically in a "for ... in open..." statement?

jfong at ms4.hinet.net jfong at ms4.hinet.net
Wed Feb 17 20:29:17 EST 2016


The "for ... open ..." is definitely not a good design pattern. It opens a file at "for" block but leaves it closed somewhere in the sky.

> The garbage collector will:
> - reclaim the memory used by the object;
> - close the file. 

I suppose (IMO) that the primitive idea of garbage collection doing the file-close affair is to make itself a final defense to prevent the possible disaster. (after all it's not of his business:-) But some coding may abuse this advantage and forget its hidden danger.

It's better to drop this "for...open..." style completely and stick at "with".

Thanks for all you gurus clarify my puzzle. I deeply appreciated it.

--Jach




More information about the Python-list mailing list