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

前端 未结 4 1767
栀梦
栀梦 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:43

    Python uses reference counting and deterministic destruction in addition to garbage collection. When there is no more references to an object, the object is released immediately. Releasing a file closes it.

    This is different than e.g. Java where there is only nondeterministic garbage collection. This means you connot know when the object is released, so you will have to close the file manually.

    Note that reference counting is not perfect. You can have objects with circular references, which is not reachable from the progam. Thats why Python has garbage collection in addition to reference counting.

提交回复
热议问题