for line in file:
print line
在上面的代码中,当我把它改成:
for line in file:
print line + " just a string"
这只会在最后一行附加“只是一个字符串”
PS:Python新手
最佳答案
遍历文件包括行尾,所以只需删除它们:
for line in file:
print line.rstrip("\n"), "something"
请注意,print 将附加其自己的换行符,因此即使不附加“某物”,您也想这样做(或使用 sys.stdout.write 而不是 print)。如果您想删除所有尾随空格(例如空格和制表符),您也可以使用 line.rstrip()
。
文档:
Files support the iterator protocol. Each iteration returns the same result as file.readline(), and iteration ends when the readline() method returns an empty string.
关于python - 如何读取行(从文件中)然后在python中附加+打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1759193/