Python—如何将“操作系统级句柄转换为打开的文件”转换为文件对象?

2024-10-01 09:34:19 发布

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

tempfile.mkstemp()返回:

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

Tags: inimportanthatosopentempfilefile
3条回答

你可以用

os.write(tup[0], "foo\n")

给手柄写信。

如果要打开用于写入的句柄,需要添加“w”模式

f = os.fdopen(tup[0], "w")
f.write("foo")

您忘记在fdopen()中指定打开模式('w')。默认值为“r”,导致write()调用失败。

我认为mkstemp()创建的文件仅供读取。用'w'调用fdopen可能会重新打开它进行写入(您可以重新打开mkstemp创建的文件)。

以下是如何使用with语句执行此操作:

from __future__ import with_statement
from contextlib import closing
fd, filepath = tempfile.mkstemp()
with closing(os.fdopen(fd, 'w')) as tf:
    tf.write('foo\n')

相关问题 更多 >