我不太确定你是否真的想删除所有转义字符\n
每行末尾的所有转义字符。这是许多 python 程序员第一次阅读文件时的常见问题,我前一段时间自己也遇到过。
readlines()
保留尾随\n
,以便简单"".join(lines)
地恢复原始文件内容。
\n
只需从每行中删除尾随。
# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys
lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
print line
lines1.append(line)
fh.close()
lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
line = line.rstrip()
print line
lines2.append(line)
fh.close()
输出将是
# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys
lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
print line
lines1.append(line)
fh.close()
lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
line = line.rstrip("\n")
print line
lines2.append(line)
fh.close()
# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys
lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
print line
lines1.append(line)
fh.close()
lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
line = line.rstrip("\n")
print line
lines2.append(line)
fh.close()
你也可以写line.rstrip("\n")
明确地只去除换行符而不是所有的空白字符。