Windows上python中的二进制和文本I / O之间的区别 [英] Difference between binary and text I/O in python on Windows
问题描述
我知道应该使用rb
而不是r
来打开一个二进制文件,因为Windows的行为对于二进制和非二进制文件是不同的。但是我不明白如果我以错误的方式打开一个文件,为什么这个区别甚至是必要的。其他操作系统似乎做的很好,通过处理这两种文件相同。
这种模式是关于行结束的转换。当以文本模式读取时,平台的本地行结束符(Windows上的 \r\\\
)是转换为Python的Unix风格
\\\
行尾。在文本模式下写入时,会发生相反的情况。
在二进制模式下,不会进行这样的转换。
其他平台通常在没有转换的情况下可以很好地工作,因为它们原生地存储行结尾为 \\\
。 (Mac OS是一个例外,过去使用
\ r
)。但是,依赖于此的代码是不可移植的。
I know that I should open a binary file using "rb"
instead of "r"
because Windows behaves differently for binary and non-binary files.
But I don't understand what exactly happens if I open a file the wrong way and why this distinction is even necessary. Other operating systems seem to do fine by treating both kinds of files the same.
This mode is about conversion of line endings.
When reading in text mode, the platform's native line endings (\r\n
on Windows) are converted to Python's Unix-style \n
line endings. When writing in text mode, the reverse happens.
In binary mode, no such conversion is done.
Other platforms usually do fine without the conversion, because they store line endings natively as \n
. (An exception is Mac OS, which used to use \r
in the old days.) Code relying on this, however, is not portable.
这篇关于Windows上python中的二进制和文本I / O之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!