为什么 os.fdopen 忽略模式?

Why does os.fdopen ignore mode?

这段代码在 Python 2.7.16 和 3.8.3 上 运行 时产生不同的结果:

import tempfile
import os

fd, lockfile = tempfile.mkstemp()
flags = os.O_RDWR | os.O_CREAT
mode = 'w+b'

fd = os.open(lockfile, flags)
fileobj = os.fdopen(fd, mode)

print(fileobj.mode)

os.remove(lockfile)

在 2.7 中它按预期打印 w+b 但在 3.8 中它打印 rb+。为什么它不以这种方式尊重模式参数?

我已经尝试手动创建一个文件来消除 tempfile 差异,但仍然得到相同的结果。

我在文档中看不到任何明显的内容:

运行 MacOS 10.14.6

我不确定 Python 是否跟踪了这一点,但考虑到你在 os.open 中使用的 flags,我会说 rb+ 实际上是正确的。

您使用标志“read/write”和“如果不存在则创建”调用了 os.open,但没有“截断”(O_TRUNC)。这正是模式 rb+wb+ 之间的区别。假设 Python 追踪到您的 flags,这是正确的模式。

来自内置 open 函数的文档:

mode is an optional string that specifies the mode in which the file is opened.

当使用文件描述符而不是文件路径调用 open 时(或者当您使用需要文件描述符的别名 fdopen 时),不会打开任何文件。创建并返回一个包装文件描述符的 Python 类文件对象。您无法更改打开文件的模式,因此 mode 参数将被忽略。