Closing a file without knowing its handle

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): # a function that I can't modify myfile = open(mypath, 'w') myfile.write('some text') myfile.flush() # to make sure 'some text' is actually written to disc file. raise Exception('An error occured') myfile.write('some stuff that will never be written') myfile.close() def del_file(mypath): # *** put something here that will close the file *** os.remove(mypath) # throws an error because file is still in use return mypath = 'g:/test.txt' try: blackbox(mypath) except: # all exceptions del_file(mypath) # clean up raise # raise whatever exception got thrown 

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 .

+5
source share

Source: https://habr.com/ru/post/1265519/


All Articles