试图找出为什么这些意外的换行符会在一个简单的脚本中打印出来。我想要在这个脚本中做的就是读取一个文件,并打印每一行的内容。
代码是这样的:
#!/usr/bin/python
import sys
# This script should just iterate over a file and echo the contents of each line
f=open(sys.argv[1],'r')
for line in f:
line.rstrip('\n')
print "Line 1 is: " + line
f.close()
输入文件只有 2 行:
#cat users
root
dontexist
#
当我使用此输入文件运行脚本时,输出中有额外的换行符:
#./test.py users
Line 1 is: root
Line 1 is: dontexist
#
我错过了什么?谢谢大家。
最佳答案
rstrip 和类似的函数(例如,replace、strip 等)返回包含已更改字符串的副本,而不是就地更改字符串。您想要执行 line = line.rstrip("\n")
关于python - Python 中打印意外的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26456639/