1、问题
在文本中,每行结尾有个'\n',举个例子,
f = open("log.txt")
logs = f.readlines()
for log in logs:
print(log)
f.close()
print(logs)
输出
2019-07-01 08:23:07,574 - __main__ - INFO - Start print log
2019-07-01 08:23:07,575 - __main__ - WARNING - Something maybe fail.
2019-07-01 08:23:07,575 - __main__ - INFO - Finish
['2019-07-01 08:23:07,574 - __main__ - INFO - Start print log\n', '2019-07-01 08:23:07,575 - __main__ - WARNING - Something maybe fail.\n', '2019-07-01 08:23:07,575 - __main__ - INFO - Finish\n']
可以看出每行输出log有个空行,logs里面每行结尾有个‘\n’,
2、解决'\n'方法
2.1 通过splitlines
f = open("log.txt")
logs = f.read().splitlines()
for log in logs:
print(log)
f.close()
print(logs)
2.2 通过strip
f = open("log.txt")
logs = f.readlines()
log_new = []
for log in logs:
print(log.strip('\n'))
log_new .append(log.strip('\n'))
f.close()
print(log_new)
2.3 通过join和strip
f = open("log.txt")
logs = f.readlines()
f.close()
log_new = ''.join(logs).strip('\n')
print(log_new)
注:strip是字符串的属性,f.readlines返回的是一个列表。既然f.readlines()返回的是列表,而strip是字符串的属性,不难想到只要我们将f.readlines()返回的列表转换成字符串就能 用strip这个属性了。那么怎么将列表转为字符串呢?这里用的是字符串的join属性。