On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
现代方式:使用newline=''
使用
newline=
关键字参数来io.open()使用Unix样式的LF行结束符:这在Python2.6+中有效。在Python 3中,还可以使用内置的
open()
函数的newline=
参数,而不是io.open()
。旧方法:二进制模式
防止换行转换的旧方法(在Python 3中不起作用)是以二进制模式打开文件,以防止换行字符的转换:
但是在Python 3中,二进制模式将读取字节而不是字符所以它不会做您想要的事情。尝试在流上执行字符串I/O时,可能会出现异常。(例如,“TypeError:”str“不支持缓冲区接口”)。
打开文件时需要使用二进制伪模式。
对于Python 2&3
请参阅本页上的The modern way: use newline=''答案。
仅适用于Python2(原始答案)
以二进制方式打开文件以防止行尾字符的转换:
引用Python手册:
相关问题 更多 >
编程相关推荐