python如何关闭已被gc化的文件? [英] How does python close files that have been gc'ed?

查看:217
本文介绍了python如何关闭已被gc化的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为如果一个文件没有被关闭就会被泄露,但我刚刚证实,如果我输入以下代码行,文件将关闭:

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

出于纯粹的好奇心,这是如何工作的?我注意到该文件不包含 __ del __ 方法。

Objects / fileobject.c 中的 file_dealloc 函数。对于C类型,除非没有 __ del __ 中固有的一些问题,否则dealloc方法就像 __ del __ p>

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:

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

Just out of sheer curiosity, how does this work? I notice that file doesn't include a __del__ method.

解决方案

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__.

这篇关于python如何关闭已被gc化的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆