文件被删除时出错

import gc import os gc.disable() open('tmp.txt', 'w').close() class A: def __init__(self): self.fo = open('tmp.txt') a = A() os.remove('tmp.txt') 

当我执行该脚本时,我得到了一个PermissionError: [WinError 32] 。然后我尝试这个:

 import gc import os gc.disable() open('tmp.txt', 'w').close() class A: def __init__(self): self.fo = open('tmp.txt') a = A() # or a = None del a os.remove('tmp.txt') 

虽然这次成功了,但是我不知道原因。 你能告诉我为什么吗?

我的Python版本是3.5.2。

在Windows上你不能删除一个文件,如果一些程序有一个句柄。

当你删除你的实例时,你手动/强制垃圾收集句柄(因为没有其他对象有一个参考),并关闭文件,这说明它的工作。

也看到如何释放在python列表中使用过的内存? 在那里解释说

 del a 

要么

 a = None 

立即释放a没有其他对象的引用的记忆。