先说结论:
- 很多博客或者资料中说windows的换行符是\r\n, linux中的换行符是\n,macos中的换行符是\r,实际上很早macos就改成\n了,参考: stackoverflow.com/questions/2…
- 文本文件和二进制文件之分: 在windows中,是区分文件文件和二进制文件的,如果是文本文件(mode=r),那么读取文件时会自动将\r\n转换为\n,如果是二进制文件读取方式,则不会转换,写入时同理,如果是写入文本文件(mode=w),会自动将\n转换为\r\n.在posix兼容系统中,不区分二进制文件和文本文件,不会做此转换
- 所以,如果不想让转换发生,需要以二进制方式读取文件:mode=rb,或者二进制方式写入文件:mode=wb,b代表二进制访问
- 关于mode=U的作用:在posix系统中,不会自动转换换行,所以如果想将\r\n自动转换为\n,需要使用rU模式,注意,只支持读,不支持写
- \r表示将光标的位置回退到本行的开头位置
常见场景
- 如何做到兼容读,即无论目标文件中是 \r\n 还是\n读取到内存中都是\n?
使用rU模式,在win系统中,只需要r模式即可,因为win系统对待文本文件会自动转码,但是其他系统比如mac,linux不区分文本文件和二进制文件,需要使用rU,总之使用rU即可
2. 场景2:如何做到写入的换行符总是 \n
wb
3. 如何做到在windows中写入\r\n,其他平台写入\n?
w
4. 如何做到所读入的数据为原始数据,而不是转换过换行的数据:
rb
实验代码
- windows系统,pytho2.7
# a.txt内容为: "hello\r\nworld"
with open('a.txt', 'rU') as f:
s = f.read()
print s == 'hello\nworld'
# a.txt内容为: "hello\r\nworld"
with open('a.txt', 'r') as f:
s = f.read()
print s == 'hello\nworld'
# a.txt内容为: "hello\r\nworld"
with open('a.txt', 'rb') as f:
s = f.read()
print s == 'hello\nworld'
print s == 'hello\r\nworld'
with open('b.txt', 'w') as f2:
f2.write('hello\n')
f2.write('world')
with open('c.txt', 'wb') as f3:
f3.write('hello\n')
f3.write('world')
with open('d.txt', 'w') as f4:
f4.write('hello\r\n')
f4.write('world')
输出结果:
True
True
False
True输出文件内容:
b.txt
c.txt
d.txt
2.macOS系统,python2.7
# a_win.txt内容为:"hello\r\nhello"
with open('a_win.txt', 'r') as f:
s = f.read()
print s == 'hello\r\nworld'
print s == 'hello\nworld'
# a_win.txt内容为:"hello\r\nhello"
with open('a_win.txt', 'rU') as f:
s = f.read()
print s == 'hello\r\nworld'
print s == 'hello\nworld'
输出结果:
True
False
False
True参考: