[英]write to previous line in python
I am writing code to generate words from one file to another I have done all ok but the problem that when I use line it feed a new line in the output file I want to next word after line to be written at the same line我正在编写代码来生成从一个文件到另一个文件的单词我已经完成了一切,但问题是当我使用 line 它在输出文件中输入一个新行我想在同一行写下一行
the code编码
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write("<answer>" + line +"doit");
now doit comes in a new line in the out.txt现在 doit 在 out.txt 中出现了一个新行
the text file has 3 lines door window house文本文件有 3 行门窗房子
The problem is that your variable line
contains a \\n
at the end, which you have to remove yourself:问题是你的变量
line
末尾包含一个\\n
,你必须自己删除它:
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write("<answer>" + line[:-1] +"doit")
The problem of using rstrip
as the other answer suggests is that you would lose ending spaces: ' aa \\n'.rstrip()
gives you ' aa'
.使用
rstrip
作为另一个答案的问题是你会失去结尾空格: ' aa \\n'.rstrip()
给你' aa'
。 This might or might not be what you need.这可能是也可能不是您需要的。
Use rstrip()
to remove the trailing \\n
使用
rstrip()
删除尾随\\n
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write("<answer>" + line.rstrip('\n') +"doit");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.