How To Used Namedtemporaryfile (and When Is It Closed?)
I'm trying to write a series of functions that writes to a temporary file, then does stuff with the written file. I'm trying to understand how the file is dealt with. What I'd lik
Solution 1:
You're writing to the file, but then you're attempting to read it from the end of your writes. Add a seek
before you start reading, to go back to the beginning of the file:
def check_file(open_file):
lines = 0
open_file.seek(0)
for line in open_file:
iflines < 5:
print line
lines += 1else:
break
For your second question, note that NamedTemporaryFile
works like TemporaryFile
in that:
It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected).
If you open the file in a function and then return, the file goes out of scope and will be closed and garbage collected. You'll need to keep a reference to the file object alive in order to keep it from being collected. You can do this by returning the file object from the function (and making sure you assign it to something). Here's a trivial example:
defmycreate():
return NamedTemporaryFile()
defmywrite(f, i):
f.write(i)
defmyread(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)
Post a Comment for "How To Used Namedtemporaryfile (and When Is It Closed?)"