gpt4 book ai didi

Python - 如何将 "an OS-level handle to an open file"转换为文件对象?

转载 作者:IT老高 更新时间:2023-10-28 20:31:50 26 4
gpt4 key购买 nike

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

最佳答案

你可以使用

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

写入句柄。

如果要打开句柄进行书写需要添加"w"模式

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

关于Python - 如何将 "an OS-level handle to an open file"转换为文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/168559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com