tempfile.mkstemp的text参数作用及是否为Windows专属?
1. text参数是Windows系统专属吗?
不是。这个参数在Unix/Linux系统里也能正常使用,但它的实际差异主要体现在Windows上——Unix/Linux中文本模式和二进制模式的区别微乎其微,几乎可以忽略。
2. text参数到底有什么用?
mkstemp的text参数用来控制临时文件以文本模式还是二进制模式打开,底层是通过调整os.open的标志位实现的:
- 当
text=True时,文件以文本模式打开:- Windows系统下:会自动做换行符转换(写入
\n会转成\r\n,读取时再反向转换),同时不会设置O_BINARY标志; - Unix/Linux系统下:因为系统本身就用
\n作为换行符,不需要额外转换,所以文本模式和二进制模式基本没区别,这个参数更多是为了保持跨平台接口的一致性。
- Windows系统下:会自动做换行符转换(写入
- 当
text=False(默认值)时,文件以二进制模式打开:- Windows系统下:会添加
O_BINARY标志,禁止换行符自动转换,读写严格按原始字节处理; - Unix/Linux系统下:和文本模式行为几乎一致,因为系统本身不区分两种模式的换行逻辑。
- Windows系统下:会添加
你提到的“底层所有文件都是字节”没错,文本模式本质是在字节流之上套了一层编码、换行转换的封装,二进制模式则直接操作原始字节。需要注意的是,mkstemp返回的是系统级文件描述符,这个描述符本身不区分模式,但后续如果用这个描述符创建文件对象(比如os.fdopen),模式就会直接影响读写行为。
参考文档摘选
If text is specified and true, the file is opened in text mode. Otherwise, (the default) the file is opened in binary mode.
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.
In particular, on Windows adding O_BINARY is needed to open files in binary mode.
示例代码
>>> import tempfile >>> tempfile.mkstemp(text=False) (3, '/tmp/tmp9z8rp2_2') >>> tempfile.mkstemp(text=True) (4, '/tmp/tmpc6z9j2yu')
内容的提问来源于stack exchange,提问作者VPfB

