Closing a file so I can delete it on Windows in Python?

So, imagine you have a python black_box module that you import into your python script. You pass the file path to this black_box module like this:

import black_box
import os

file_path = r"C:\foo.txt"
black_box.do_something(file_path)
os.remove(file_path)

      

Sometimes black_box modules open this file and leave it open, but I need to delete this file which black_box opened.

I am getting an error on Windows:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: C: \ foo.txt

How do I close a file to delete it?

I cannot change the black_box module.

I don't have a file handler generated by black_box.

black_box prevents the file from being closed.

+3


source to share


1 answer


Since you don't have access to the black box, you can use taskkill

import os
os.system("taskkill /im blackbox.exe")

      



Then you can delete your file and side effect, your black box will stop.

0


source







All Articles