我有一个功能(我无法修改)试图打开一个文件但在进程中抛出一个异常(我的MWE中的blackbox
,一个从模块实际导入的函数)。我试图编写一些异常处理代码来删除blackbox
尝试编写的垃圾文件。但是,我不能,因为该文件仍处于打开状态,我不知道如何在不知道文件句柄(myfile
)的情况下关闭它。
这就是我的MWE的样子:
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
在os.remove(mypath)
我收到以下错误:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'g:/test.txt'
现在我的问题:
如何关闭并删除打开的文件,知道mypath
但不操纵blackbox
?
上面的代码是为Windows 7编写的,但我认为答案应该适用于所有操作系统。您可能需要更改mypath
。