在不知道文件的手的情况下关闭文件

2024-06-02 13:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数(我不能修改),它试图打开一个文件,但在这个过程中抛出了一个异常(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

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 上面的代码是为Windows7编写的,但我认为答案应该适用于所有操作系统。您可能需要更改mypath。你知道吗


Tags: 文件函数代码thatisosdefsome