我正在编写代码以生成从一个文件到另一个文件的单词,我已经做得很好,但问题是,当我使用行时,它会在输出文件中输入一个新行,我想在同一行中写下一个又一行代码with open("test.txt") as f: with open("out.txt", "w") as f1: for line in f: f1.write("<answer>" + line +"doit"); 现在 doit 进来了一条新的线在外面.txt文字文件有3行门窗屋
2 回答

人到中年有点甜
TA贡献1895条经验 获得超7个赞
问题是你的变量在末尾包含一个,你必须自己删除它: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")
使用另一个答案所建议的问题在于,您将丢失结束空格:给你。这可能是也可能不是您需要的。rstrip' aa \n'.rstrip()' aa'

慕标琳琳
TA贡献1830条经验 获得超9个赞
用于删除尾随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");
添加回答
举报
0/150
提交
取消