How does python close files that have been gc'ed?

前端 未结 4 1769
栀梦
栀梦 2020-11-30 14:41

I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close:

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 15:44

    Best guess is that because the file type is a built-in type, the interpreter itself handles closing the file on garbage collection.

    Alternatively, you are only checking after the python interpreter has exited, and all "leaked" file handles are closed anyways.

提交回复
热议问题