How does python close files that have been gc#39;ed?(python如何关闭已被gced的文件?)
问题描述
我一直认为如果文件打开而不关闭就会泄漏,但我只是验证了如果我输入以下代码行,文件就会关闭:
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
纯粹出于好奇,这是如何工作的?我注意到该文件不包含 __
del__
方法.
Just out of sheer curiosity, how does this work? I notice that file doesn't include a __
del__
method.
推荐答案
至少在 CPython 中,文件对象在释放时会关闭.请参阅 CPython 源代码中 Objects/fileobject.c
中的 file_dealloc
函数.Dealloc 方法有点像 C 类型的 __del__
,除了没有 __del__
固有的一些问题.
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'ed的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python如何关闭已被gc'ed的文件?


基础教程推荐
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01