无法在mkstemp中使用fdopen
我无法通过 fdopen
从 mkstemp
返回的句柄写入以 rw
模式打开的文件。
>>> 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
>>>
奇怪的是,我可以从以 rw
模式打开的文件中读取内容:
>>> g = tempfile.mkstemp()
>>> h = os.fdopen(g[0], "rw")
>>> h.read()
''
如果我以某种模式打开文件,事情就没问题了:
>>> 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")
>>>
1 个回答
3
rw
不是一个有效的模式。
如果你想以更新模式(既可以读又可以写)打开文件,可以使用 w+
或 r+
模式。
(可以查看 open
的文档:os.fdopen
的 mode
参数和 open
是一样的。)