无法将fdopen与mkstemp一起使用

2024-10-01 09:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法从mkstemp返回的句柄写入由fdopen作为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

^{pr2}$

如果我以一种或另一种模式打开文件,则一切正常:

>>> 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")
>>> 

Tags: 文件importfooosmodeopentempfile句柄