问题是你的变量在末尾包含一个,你必须自己删除它:line\nwith 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'
用于删除尾随rstrip()\nwith open("test.txt") as f: with open("out.txt", "w") as f1: for line in f: f1.write("<answer>" + line.rstrip('\n') +"doit");