Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NamedTemporaryFile().write (without intermediate variable) result in "I/O operation on closed file"?

I have the following script, which does the same thing twice, in very slightly different ways. The first works, the second does not:

#!/usr/bin/python
import tempfile

fhandle=tempfile.NamedTemporaryFile(dir=".",delete=False)
fhandle.write("hello")

tempfile.NamedTemporaryFile(dir=".",delete=False).write("hello")

I get the follow error:

Traceback (most recent call last):
  File "./test.py", line 7, in <module>
     tempfile.NamedTemporaryFile().write("hello")
 ValueError: I/O operation on closed file

In my example script, I have put them together to show that the first one works. This does not affect the results, just points out that there is a difference.

Is this a bug in Python? Something weird about my machine? Expected behaviour? Correct behaviour? It looks like the object is being destroyed before the write().

Python 2.7.3 on Ubuntu 12.04.3 LTS

like image 579
AMADANON Inc. Avatar asked Nov 01 '22 15:11

AMADANON Inc.


1 Answers

Correct answer (from both answers to this question, and further test): This is a bug.

I have raised a bug, which can be seen here: http://bugs.python.org/issue18879

like image 148
AMADANON Inc. Avatar answered Nov 15 '22 05:11

AMADANON Inc.