Python 写入文件换行符问题及解决方案
这是因为在Windows中,换行符由'\r\n'表示。而在Unix和Linux中,换行符只由'\n'表示。
在写入文件时,使用'\r\n'作为换行符会被解释为两个换行符,导致每行之间有一个空行。
要解决这个问题,可以在写入文件时使用'\n'作为换行符,或者在读取文件时处理换行符的差异。以下是两种解决方法:
- 在写入文件时使用'\n'作为换行符:
s = '1\n2\n3'
with open('test.txt', 'w', encoding='utf-8') as f:
f.write(s)
- 在读取文件时处理换行符的差异:
with open('test.txt', 'r', encoding='utf-8') as f:
content = f.read()
lines = content.split('\n')
for line in lines:
print(line)
无论哪种方法,都可以正确地输出:
1
2
3
原文地址: https://www.cveoy.top/t/topic/o7lF 著作权归作者所有。请勿转载和采集!