Dar*_*zer 50 python mkstemp fdopen temporary-files
一个元组,包含一个打开文件的操作系统级句柄(由os.open()返回)和该文件的绝对路径名,按顺序排列.
如何将操作系统级别的句柄转换为文件对象?
要将文件描述符包装在"文件对象"中,请使用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
Run Code Online (Sandbox Code Playgroud)
Pet*_*ann 51
您可以使用
os.write(tup[0], "foo\n")
Run Code Online (Sandbox Code Playgroud)
写入句柄.
如果要打开用于写入的句柄,则需要添加"w"模式
f = os.fdopen(tup[0], "w")
f.write("foo")
Run Code Online (Sandbox Code Playgroud)
Dar*_*zer 13
以下是使用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')
Run Code Online (Sandbox Code Playgroud)
你忘了在fdopen()中指定打开模式('w').默认值为'r',导致write()调用失败.
我认为mkstemp()创建的文件只供阅读.用'w'调用fdopen可能会重新打开它以进行写入(您可以重新打开由mkstemp创建的文件).