python – I/O stream: why there is no error when working with files without explicitly closing them

Question:

I'm trying these designs:

file = open('file.txt').read()
open('copy_file.txt', 'w').write(file)

For some reason it works… From my experience with other languages, I expected to see some oddities with open streams (I don't close them), but everything works fine. Even after multiple launches. And it doesn't look like there is a memory leak issue. Why is that ? I didn't find anything in the documentation about this…

Answer:

You only use memory to store the contents of file.txt in the file variable.

And open streams are closed and collected by the garbage collector as soon as the read or write ends, since you do not have references to these objects.

You can read about the assembly at this link: http://arctrix.com/nas/python/gc/

Scroll to Top