a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.
如何将操作系统级句柄转换为文件对象?
documentation for os.open()声明:
To wrap a file descriptor in a "file object", use fdopen().
所以我试着:
>>> import tempfile
>>> tup = tempfile.mkstemp()
>>> import os
>>> f = os.fdopen(tup[0])
>>> f.write('foo\n')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor
你可以用
给手柄写信。
如果要打开用于写入的句柄,需要添加“w”模式
您忘记在fdopen()中指定打开模式('w')。默认值为“r”,导致write()调用失败。
我认为mkstemp()创建的文件仅供读取。用'w'调用fdopen可能会重新打开它进行写入(您可以重新打开mkstemp创建的文件)。
以下是如何使用with语句执行此操作:
相关问题 更多 >
编程相关推荐