python - How to used NamedTemporaryFile (and when is it closed?) -
i'm trying write series of functions writes temporary file, stuff written file. i'm trying understand how file dealt with.
what i'd in abstract is:
def create_function(inputs): # create temp file, write contents def function1(file): # stuff temp file def function2(file): # other stuff temp file
so can like:
my_file = create_function(my_inputs) function1(my_file) function2(my_file)
so here's i've done:
def db_cds_to_fna(collection, open_file): """ pulls data mongodb , writes temporary file - writing arbitrary string doesn't alter question (i'm pretty sure) """ 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 line in open_file: if lines < 5: print line lines += 1 else: break
with code, if run following:
from tempfile import namedtemporaryfile tmp_file = namedtemporaryfile() tmp_fna = db_cds_to_fna('test_collection', tmp_file) check_file(tmp_file)
this code runs, doesn't print anything. file there , written, because if run print popen(['head', tmp_fna], stdout=pipe)[0]
, expected beginning of file. or, if change check_file()
accept tmp_file.name
, with open(tmp_file.name, 'r')...
inside function, works.
so question 1 - why can write tmp_file
, can't read different function without re-opening it?
now, i'd have tmp_file = namedtemporaryfile()
inside db_cds_to_fna()
function, when try , run:
tmp_fna = db_cds_to_fna('test_collection') check_file(tmp_file)
i error no such file or folder
so question 2 is: there way keep temporary file around function use? know how write file specified path , delete it, suspect there's built in way , i'd learn.
you're writing file, you're attempting read end of writes. add seek
before start reading, go beginning of file:
def check_file(open_file): lines = 0 open_file.seek(0) line in open_file: if lines < 5: print line lines += 1 else: break
for second question, note namedtemporaryfile
works temporaryfile
in that:
it destroyed closed (including implicit close when object garbage collected).
if open file in function , return, file goes out of scope , closed , garbage collected. you'll need keep reference file object alive in order keep being collected. can returning file object function (and making sure assign something). here's trivial example:
def mycreate(): return namedtemporaryfile() def mywrite(f, i): f.write(i) def myread(f): f.seek(0) return f.read() f = mycreate() # 'f' reference file created in function, # keep being garbage collected mywrite(f, b'hi') myread(f)
Comments
Post a Comment