python - Why does NamedTemporaryFile().write (without intermediate variable) result in "I/O operation on closed file"? -
i have following script, same thing twice, in different ways. first works, second not:
#!/usr/bin/python import tempfile fhandle=tempfile.namedtemporaryfile(dir=".",delete=false) fhandle.write("hello") tempfile.namedtemporaryfile(dir=".",delete=false).write("hello")
i 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 example script, have put them show first 1 works. not affect results, points out there difference.
is bug in python? weird machine? expected behaviour? correct behaviour? looks object being destroyed before write().
python 2.7.3 on ubuntu 12.04.3 lts
i think comments @eric urban , @alecxe right, file closed - depending on platform - based on refcount, or similar. tried looking @ newly created tempfile object using similar process:
>>> tempfile.namedtemporaryfile().__dict__ {'close_called': true, 'name': '/tmp/tmpcrzr_c', 'file': <closed file '<fdopen>', mode 'w+b' @ 0x7f9448e541e0>, 'delete': true} >>> = tempfile.namedtemporaryfile() >>> a.__dict__ {'close_called': false, 'name': '/tmp/tmpnmwpq5', 'file': <open file '<fdopen>', mode 'w+b' @ 0x7f9448e54270>, 'delete': true}
so time after creation, close
being called on newly created temp file, there no references it. depending on platform , way call it, closing file may delete it.
Comments
Post a Comment