Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Delete locked file

Tags:

python

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'
like image 760
user3073001 Avatar asked Sep 13 '26 23:09

user3073001


1 Answers

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

like image 52
khampson Avatar answered Sep 15 '26 12:09

khampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!