Python 的 tempfile.mkstemp() 返回整数而不是文件句柄?
Python's tempfile.mkstemp() returning an integer instead of a file handle?
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])
获取文件句柄?为什么它不返回文件句柄?
这是预期的行为,因为 OS-level 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
模块的 higher-level 函数,例如 tempfile.TemporaryFile()
.
mkstemp()
returns a tuple containing an OS-level handle to an open file (as would be returned byos.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])
获取文件句柄?为什么它不返回文件句柄?
这是预期的行为,因为 OS-level 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 文件对象,只需使用 temp
模块的 higher-level 函数,例如 tempfile.TemporaryFile()
.