gpt4 book ai didi

Python 的 tempfile.mkstemp() 返回一个整数而不是文件句柄?

转载 作者:行者123 更新时间:2023-12-03 22:17:09 25 4
gpt4 key购买 nike

根据 tempfile.mkstemp docs ,

mkstemp() returns 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.



但是,从这些 shell 命令来看,元组的第一个成员似乎是一个整数,而不是文件句柄:
>>> temp = tempfile.mkstemp(suffix='.html')

>>> temp
(17, '/var/folders/dc/nv4yxcrd0zqd2dtxlj281b740000gn/T/tmpktmb2gjg.html')

>>> type(temp[0])
int

我是否必须使用 open(temp[1]) 来获取文件句柄? ?为什么它不返回文件句柄?

最佳答案

这是预期的行为,因为操作系统级别 file handles是整数。

several functions in the os module这将接受这样的整数:

These functions operate on I/O streams referenced using file descriptors.

File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.



它们不是 Python 文件对象,但您可以使用 io.FileIO() 为给定描述符创建 Python 文件对象。 .

然而,如果你想要的只是一个临时文件作为 Python 文件对象,那么只需要使用 temp 的高级函数即可。模块,如 tempfile.TemporaryFile() .

关于Python 的 tempfile.mkstemp() 返回一个整数而不是文件句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49639329/

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