I have a function (which I cannot change) that tries to open the file, but throws an exception in the process ( blackbox in my MWE, a function imported from the module in reality). I am trying to write exception handling code that will delete the garbage file that blackbox trying to write. However, I cannot, because the file is still open, and I do not know how to close it without knowing the file descriptor ( myfile ).
Here's what my MWE looks like:
import os def blackbox(mypath):
On os.remove(mypath) I get the following error:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'g:/test.txt'
Now my question is: How to close and delete an open file, knowing mypath , but without using blackbox ? The code above is written for Windows 7, but I think the answers should be applicable to all operating systems. You may need to modify mypath .
source share