我正在尝试编写一系列写入临时文件的函数,然后对写入的文件进行处理。我试图了解该文件是如何处理的。
我想做的摘要是:
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
and do with open(tmp_file.name, 'r')...
在函数内部,它起作用了。
所以问题 1 是 - 为什么我可以写信给tmp_file
,但是如果不重新打开它就无法从不同的函数中读取它?
现在,我真正想做的是tmp_file = NamedTemporaryFile()
在 - 的里面db_cds_to_fna()
函数,但是当我尝试这个并运行时:
tmp_fna = db_cds_to_fna('test_collection')
check_file(tmp_file)
我收到一个错误No such file or folder
所以问题 2 是:有没有办法保留临时文件以供另一个函数使用?我知道如何将文件写入指定路径然后删除它,但我怀疑有一种内置方法可以做到这一点,我想学习。