Python - 如何将操作系统级别的句柄转换为打开的文件”到文件对象?
-
03-07-2019 - |
题
包含打开文件的操作系统级句柄(由os.open()返回)的元组,以及该文件的绝对路径名。
如何将操作系统级别的句柄转换为文件对象?
os.open()的文档陈述:
将文件描述符包装在“文件中” object“,”使用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")
写入句柄。
如果您要打开手柄进行书写,则需要添加&quot; w&quot; 模式
f = os.fdopen(tup[0], "w")
f.write("foo")
其他提示
以下是使用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')
您忘了在fdopen()中指定打开模式('w')。默认值为'r',导致write()调用失败。
我认为mkstemp()创建的文件仅供阅读。用'w'调用fdopen可能会重新打开它进行写入(你可以重新打开由mkstemp创建的文件)。
temp = tempfile.NamedTemporaryFile(delete=False)
temp.file.write('foo\n')
temp.close()
你的目标是什么? tempfile.TemporaryFile
是否适合您的目的?
我无法对答案发表评论,所以我将在此发表评论:
要创建用于写访问的临时文件,可以使用tempfile.mkstemp并指定“w”。作为最后一个参数,如:
f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'...
os.write(f[0], "write something")
不隶属于 StackOverflow