猿问

写入蟒蛇中的上一行

我正在编写代码以生成从一个文件到另一个文件的单词,我已经做得很好,但问题是,当我使用行时,它会在输出文件中输入一个新行,我想在同一行中写下一个又一行


代码


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行门窗屋


潇湘沐
浏览 69回答 2
2回答

人到中年有点甜

问题是你的变量在末尾包含一个,你必须自己删除它:line\nwith open("test.txt") as f:&nbsp; &nbsp; with open("out.txt", "w") as f1:&nbsp; &nbsp; &nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f1.write("<answer>" + line[:-1] +"doit")使用另一个答案所建议的问题在于,您将丢失结束空格:给你。这可能是也可能不是您需要的。rstrip'&nbsp; aa&nbsp; \n'.rstrip()'&nbsp; aa'

慕标琳琳

用于删除尾随rstrip()\nwith open("test.txt") as f:&nbsp; &nbsp; with open("out.txt", "w") as f1:&nbsp; &nbsp; &nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f1.write("<answer>" + line.rstrip('\n') +"doit");&nbsp;&nbsp;
随时随地看视频慕课网APP

相关分类

Python
我要回答