Python 为什么按行读取 txt 文本列表每一行都带了 \n

2017 年 8 月 18 日
 fearme
不能自动去掉 \n 么
18119 次点击
所在节点    Python
54 条回复
Patrick95
2017 年 8 月 18 日
换行符。
要去掉的话:
for line in file.readlines():
line=line.strip('\n')
xingzhi1990
2017 年 8 月 18 日
Python 不会自动去掉换行符的。
with open('test.txt', 'r') as f:
lines = [line.strip() for line in f.readlines()]

使用 strip()函数可以去掉行首和行尾的 whitespace,比如空格,制表符、换行符。
geeglo
2017 年 8 月 18 日
\n 是换行符。

要去掉的话,自己处理
linuap
2017 年 8 月 18 日
.rstrip("\n")
mooncakejs
2017 年 8 月 18 日
readlines 很慢的 ,, 直接 for line in file
allinwonder
2017 年 8 月 18 日
Windows 下的文本文件行末是\n\r 哦
fearme
2017 年 8 月 18 日
谢谢楼上各位的解答, 我主要是疑惑为什么还带个 '\n',以前用 delphi, 这种都是预处理掉 换行符的,所以疑惑了一下
msg7086
2017 年 8 月 18 日
@allinwonder 这是哪个位面的 Windows。
yunkchen
2017 年 8 月 18 日
@allinwonder
linux,unix:\r\n
windows:\n
Mac OS:\r
cxyfreedom
2017 年 8 月 18 日
@allinwonder
你 linux 和 windows 的搞反了吧
cxyfreedom
2017 年 8 月 18 日
@yunkchen at 错人了。你 linux 和 windows 的搞反了吧
yunkchen
2017 年 8 月 18 日
honeycomb
2017 年 8 月 18 日
@allinwonder
@yunkchen
@cxyfreedom
总之 windows 的换行符是先回车再换行
linux 只有回车,mac 只有换行
allinwonder
2017 年 8 月 18 日
@msg7086 你们是搞笑吗?

LF: Unix and Unix-like systems (Linux, macOS, FreeBSD, Multics, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others[1]

CR+LF: Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems

https://stackoverflow.com/questions/426397/do-line-endings-differ-between-windows-and-linux

I translate this into these line endings in general:

Windows: '\r\n'
Mac (OS 9-): '\r'
Mac (OS 10+): '\n'
Unix/Linux: '\n'


我 96 年开始玩电脑的,难道你们现在这些小年轻码农玩的不一样?
jarlyyn
2017 年 8 月 18 日
@allinwonder

所以我们这个位面的 windows 是 /r/n,不是 /n/r.....
livexia
2017 年 8 月 18 日
尴尬现场
Miy4mori
2017 年 8 月 18 日
尬秀现场
allinwonder
2017 年 8 月 18 日
@jarlyyn 你们这个位面的不打错字?
lslqtz
2017 年 8 月 18 日
楼上看的我一脸懵
Orzpls
2017 年 8 月 18 日
@allinwonder
你的回答才是完整的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/383883

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX