python - 如何读取行(从文件中)然后在python中附加+打印?

标签 python

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/

相关文章:

python - 如何为 neo4j 配置 django settings.py?

python - 通过python解析Json数据并更新sql表

python - 如果没有 show() 方法,matplotlib 图形不会出现

python - 在行到达时从压缩的、分块的 HTTP 流中有效地读取行

python - 如何为 python3 安装 netfilterqueue?

python - 确定Python行开头的实际文件位置

python - 需要澄清 - 使用列表的 Python For 循环

python - django 1.8 CreateView 错误

python - AWS X-Ray 在服务 map 中显示重复节点

python - 根据字符串中定义的条件填充新列