Question

I am not able write to a file opened as rw by fdopen from the handle returned by mkstemp.

>>> import tempfile
>>> import os
>>> a = tempfile.mkstemp()
>>> b = os.fdopen(a[0], "rw")
>>> b
<open file '<fdopen>', mode 'rw' at 0x7f81ea669f60>
>>> b.write("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 9] Bad file descriptor
>>> 

Curiously, I can read from a file opened rw:

>>> g = tempfile.mkstemp()
>>> h = os.fdopen(g[0], "rw")
>>> h.read()
''

If I open the file in one mode or the other then things are just fine:

>>> c = tempfile.mkstemp()
>>> d = os.fdopen(c[0], "r")
>>> d
<open file '<fdopen>', mode 'r' at 0x2380540>
>>> d.read()
''
>>> e = tempfile.mkstemp()
>>> f = os.fdopen(e[0], "w")
>>> f.write("foo")
>>> 
Was it helpful?

Solution

rw is not a valid mode.

If you want to open the file with updaing mode (reading/writing), use w+ or r+ mode.

(See open documentation: mode parameter of os.fdopen is same as open.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top