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

标签 python temporary-files mkstemp fdopen

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/

相关文章:

python 临时文件| NamedTemporaryFile 不能使用生成的临时文件

c# - 如何使用默认浏览器打开 HTML 文件并在用户查看后将其删除?

c - 为什么我不能使用动态分配的字符串创建临时文件?

c++ - 使用从 mkstemp 生成的文件名

python - Pandas:按年度百分位数对时间序列进行分箱

python - 计算特定阈值的精度和召回率

python - 使用三元运算符分配两个变量

python - 在 Python 中使用 Webbrowser 模块打开选项卡

Ruby 写入内存中的文件(实际上不是写入文件)