Python-如何将"操作系统级别的句柄转换为打开的文件"转换为文件对象?
时间:2020-03-06 15:05:35 来源:igfitidea点击:
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.
如何将操作系统级别的句柄转换为文件对象?
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
解决方案
我们可以使用
os.write(tup[0], "foo\n")
写句柄。
如果要打开书写手柄,则需要添加" w"模式
f = os.fdopen(tup[0], "w") f.write("foo")
我们忘记在fdopen()中指定打开模式('w')。默认值为" r",导致write()调用失败。
我认为mkstemp()创建的文件仅供读取。用" w"调用fdopen可能会重新打开它进行写入(我们可以重新打开由mkstemp创建的文件)。
目标是什么? tempfile.TemporaryFile
是否不适合目的?
以下是使用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')
temp = tempfile.NamedTemporaryFile(delete=False) temp.file.write('foo\n') temp.close()