Вопрос

Я всегда предполагал, что файл протекает, если он будет открыт без закрытия, но я просто подтвердил, что если я введу следующие строки кода, файл закроется:

>>> f = open('somefile.txt')
>>> del f

Просто из явного любопытства, как это работает? Я замечаю, что файл не включает __дель__ метод

Это было полезно?

Решение

В CPYTHON, по крайней мере, файлы закрыты, когда объект файла сделка. Увидеть file_dealloc функционировать в Objects/fileobject.c В источнике CPYTHON. Методы Dealloc вроде как __del__ Для типов C, за исключением некоторых проблем, присущих __del__.

Другие советы

Следовательно с утверждение.

Для Python 2.5, используйте

from __future__ import with_statement

(Для Python 2.6 или 3.x ничего не делайте)

with open( "someFile", "rU" ) as aFile:
    # process the file
    pass
# At this point, the file was closed by the with statement.
# Bonus, it's also out of scope of the with statement,
# and eligible for GC.

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.

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top