Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: need to close file from mkstemp if I use fdopen?

Which of the following is more correct?

fi, path = tempfile.mkstemp()
f = os.fdopen(fi, "w")
f.write(res)
f.close()
os.close(fi)

or:

fi, path = tempfile.mkstemp()
f = os.fdopen(fi, "w")
f.write(res)
f.close()
like image 749
Claudiu Avatar asked Oct 17 '11 21:10

Claudiu


1 Answers

Check f.fileno(), it should be the same as fi. You should only ever close that file descriptor once, so the second is correct.

On Unix, the first causes an error:

>>> f.close()
>>> os.close(fi)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor
like image 140
Andrew Clark Avatar answered Oct 07 '22 20:10

Andrew Clark