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

前端 未结 4 1757
栀梦
栀梦 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

    In CPython, at least, files are closed when the file object is deallocated. See the file_dealloc function in Objects/fileobject.c in the CPython source. Dealloc methods are sort-of like __del__ for C types, except without some of the problems inherent to __del__.

提交回复
热议问题