2

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'
user3073001
  • 269
  • 3
  • 13
  • 1
    What has the file handle? Your script? Or another program? – Cory Kramer Aug 13 '14 at 23:04
  • 2
    You need to close the program that has that file opened. – metatoaster Aug 13 '14 at 23:04
  • In the Win32 API, there is a way to open a file such that it will get deleted when the program closes. I don't know if that's exposed in Python somewhere. However, maybe you're doing this for a temporary file that you open yourself? In that case, check out the `tempfile` module. – Dirk Groeneveld Aug 13 '14 at 23:53
  • Windows doesn't allow you to delete a open file. You can only schedule its deletion. – Ross Ridge Aug 14 '14 at 01:28
  • For a Linux version see: [Detect and delete locked file in python](https://stackoverflow.com/questions/1320812/detect-and-delete-locked-file-in-python) – Evandro Coan Jan 19 '19 at 16:40

1 Answers1

2

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

khampson
  • 14,700
  • 4
  • 41
  • 43