Skip to main content
 首页 » 编程设计

Python:删除锁定的文件

2024年10月25日34fff_TT

如何使用 Python (Windows) 删除具有读取锁定的文件?

显而易见,行不通:

  import os 
  os.remove("test_file.csv") 
  Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
   WindowsError: [Error 32] The process cannot access the file because it is being 
   used by another process: 'test_file.csv' 

请您参考如下方法:

如果您想无条件地强制关闭事件句柄以便删除文件,您可以利用 Microsoft 的 handle tool使用文件名作为参数(这将返回对象名称中包含该字符串的所有文件句柄),然后使用指定 -c 选项再次调用 handle要关闭的确切句柄及其所属的 pid。

在过去我知道我想要绝对、无条件地终止特定文件/目录的事件句柄以便我可以继续执行另一个操作的情况下,我曾成功地使用过这种方法。

但是,请记住,handle 的文档指出:

WARNING: Closing handles can cause application or system instability.

您可以使用 subprocess.check_output 调用handle。

More subprocess info