Skip to main content
 首页 » 编程设计

python之如何使用 NamedTemporaryFile(何时关闭)

2025年05月04日17qlqwjy

我正在尝试编写一系列写入临时文件的函数,然后对写入的文件进行处理。我试图了解文件的处理方式。

我想在摘要中做的是:

def create_function(inputs): 
    # create temp file, write some contents 
 
def function1(file): 
    # do some stuff with temp file 
 
def function2(file): 
    # do some other stuff with temp file 

这样我就可以做类似的事情:

my_file = create_function(my_inputs) 
function1(my_file) 
function2(my_file) 

所以这是我实际做的:

def db_cds_to_fna(collection, open_file): 
    """ 
    This pulls data from a mongoDB and writes it to a temporary file - just writing an arbitrary string doesn't alter my question (I'm pretty sure) 
    """ 
    for record in db[collection].find({"type": "CDS"}): 
        open_file.write(">{}|{}|{}\n{}\n".format( 
            collection, 
            record["_id"], 
            record["annotation"], 
            record["dna_seq"] 
            ) 
        ) 
 
    return open_file.name 
 
def check_file(open_file): 
    lines = 0 
    for line in open_file: 
        if lines < 5: 
            print line 
            lines += 1 
        else: 
            break 

使用此代码,如果我运行以下命令:

from tempfile import NamedTemporaryFile 
tmp_file = NamedTemporaryFile() 
tmp_fna =  db_cds_to_fna('test_collection', tmp_file) 
 
check_file(tmp_file) 

此代码运行,但实际上并未打印任何内容。但是文件显然在那里并已写入,因为如果我运行 print Popen(['head', tmp_fna], stdout=PIPE)[0],我会得到文件的预期开头。或者,如果我更改 check_file() 以接受 tmp_file.name 并执行 with open(tmp_file.name, 'r')... 在函数内部,它起作用了。

所以问题 1 是 - 为什么我可以写入 tmp_file,但如果不重新打开它就不能从不同的函数读取它?

现在,我真正想做的是在 db_cds_to_fna() 函数中使用 tmp_file = NamedTemporaryFile(),但是当我尝试并运行时:

tmp_fna =  db_cds_to_fna('test_collection') 
check_file(tmp_file) 

我得到一个错误No such file or folder

所以问题 2 是:有没有办法保留临时文件以供其他函数使用?我知道如何将文件写入指定路径然后将其删除,但我怀疑有一种内置方法可以执行此操作,我想学习。

请您参考如下方法:

您正在写入文件,但您正试图从写入的末尾读取它。添加seek在开始阅读之前,回到文件的开头:

def check_file(open_file): 
    lines = 0 
    open_file.seek(0) 
    for line in open_file: 
        if lines < 5: 
            print line 
            lines += 1 
        else: 
            break 

对于第二个问题,请注意 NamedTemporaryFile 的工作方式类似于 TemporaryFile在那:

It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected).

如果您在函数中打开文件然后返回,文件将超出范围,将被关闭并进行垃圾回收。您需要保持对文件对象的引用处于事件状态,以防止它被收集。您可以通过从函数返回文件对象(并确保将其分配给某物)来做到这一点。这是一个简单的例子:

def mycreate(): 
    return NamedTemporaryFile() 
def mywrite(f, i): 
    f.write(i) 
def myread(f): 
    f.seek(0) 
    return f.read() 
 
f = mycreate()        # 'f' is now a reference to the file created in the function,  
                      # which will keep it from being garbage collected 
mywrite(f, b'Hi') 
myread(f)