Python文件读写时的换行符与回车符
1. 背景知识
ASCII码中的换行符与回车符:
换行符 10 LF '\n'
回车符 13 CR '\r'
在操作系统的历史中,有很多种方法来表示另起一行,但'\n'和'\r'是最常用的方式,目前主流操作系统的行结束符号如下所示:
2. 测试程序(python2.7 + win7)
(1) test1: "w"方式写时的'\n'会在被系统自动替换为'\r\n'
[python] view plain copy
# -*- coding: utf-8 -*-
def main():
try:
fout = open("test1.txt", "w")
except IOError:
print "Error: open file failed."
return
for i in range(5):
line = str(i) + "\n"
fout.write(line)
fout.close()
if __name__ == "__main__":
main()
测试结果:
(2) test2: "wb"方式写时的'\n'不会在被系统自动替换为'\r\n'
[python] view plain copy
fout = open("test2.txt", "wb")
测试结果:
(3) test3: "r"方式读时,文件中的'\r\n'会被系统替换为'\n'
另外,python提到的通用新行格式(U修饰符),个人觉得是把"r"默认"rU"的,测试中两种方式读取结果一样。
[python] view plain copy
# -*- coding: utf-8 -*-
def main():
try:
fin = open("test1.txt", "r")
except IOError:
print "Error: open file failed."
return
for line in fin:
for i in range(len(line)):
print "\t%d" % ord(line[i]),
print ""
fin.close()
if __name__ == "__main__":
main()
对于上述不同内容的两个文件输出为:
(4) test4: "rb"方式读时,文件中的'\r\n'不会被系统替换为'\n'
3. 结论 上述问题实际上自己在文件处理中遇到,文件换行中的回车符和换行符挺容易弄混,总结了一下,共大家查阅.
数据分析咨询请扫描二维码