在不知道其句柄的情况下关闭文件

Joo*_*eey 5 python file

我有一个函数(我无法修改)试图打开一个文件但在进程中抛出一个异常(blackbox在我的MWE中,一个从模块实际导入的函数).我正在尝试编写一些异常处理代码来删除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
Run Code Online (Sandbox Code Playgroud)

os.remove(mypath)我得到以下错误:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'g:/test.txt'
Run Code Online (Sandbox Code Playgroud)

现在我的问题是: 我怎么能关闭并删除打开的文件,知道mypath但没有操纵blackbox 上面的代码是为Windows 7编写的,但我认为答案应该适用于所有操作系统.你可能需要改变mypath.