【问题标题】:Writing to a new line in python in append mode以追加模式写入python中的新行
【发布时间】:2013-04-17 16:22:44
【问题描述】:

如何在 python 中为现有文件追加新行?

我的代码是:

        status_done="Completed"
        f = open("%s\%s%s" % (path,self.filename,filelog_ext),"a")
        data=("%s \r" % status_done)        
        f.writelines(data)

我试过 \r , \n ,两者都 \r\n 它们都不起作用,它总是附加到现有行的末尾

这是它给我的输出:

line1:http://www.md5.comCompleted

我希望 Completed 位于新行上,即:

line1:http://www.md5.com

line2: 完成

【问题讨论】:

    标签: python file-io append newline


    【解决方案1】:

    怎么样

    data="\r\n%s" % status_done  
    f.write(data)
    

    作为进一步解释,您在“完成”之后添加换行符......这只是将换行符移动到您的字符串之前,以便您的字符串出现在换行符上

    【讨论】:

    • 如果你把它变成tuple或者如果OP只使用f.write,这可能会更有效
    【解决方案2】:

    你也可以使用

    with open("File.txt", "ab") as myfile:
    

    "ab" 将使其以二进制模式附加,其中包括转义的行字符。

    【讨论】:

      猜你喜欢
      • 2019-06-10
      • 1970-01-01
      • 2011-06-14
      • 2021-03-12
      • 2016-10-21
      • 1970-01-01
      • 2020-09-02
      • 2016-12-25
      • 1970-01-01
      相关资源
      最近更新 更多