user3073001
user3073001

Reputation: 279

Python: Delete locked file

How do I delete a file with Python (Windows) that has a read lock?

The obvious, doesn't work:

  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'

Upvotes: 3

Views: 5147

Answers (1)

khampson
khampson

Reputation: 15336

If you want to unconditionally force the closure of the active handle so you can delete the file, you could leverage Microsoft's handle tool using the file name as the argument (which will return all file handles with that string in the object name), and then the invoke handle again using the -c option specifying the exact handle to close and the pid it belongs to.

I have used this method successfully in the past in cases where I knew I wanted to absolutely, unconditionally kill the active handles on a particular file/directory so I could proceed with another action.

However, keep in mind that, as the documentation for handle states:

WARNING: Closing handles can cause application or system instability.

You can use subprocess.check_output to invoke handle.

More subprocess info

Upvotes: 2

Related Questions