【问题标题】:Python: to write additional text in the txt filePython:在 txt 文件中写入附加文本
【发布时间】:2021-10-17 04:30:04
【问题描述】:

当我使用函数 write 时,然后在 txt 文件中获取所有新文本。我需要在文件中添加附加文本而不删除旧文本。这可能吗?

问候, 马吕斯

【问题讨论】:

    标签: python function file text write


    【解决方案1】:

    尝试在a模式下阅读:

    with open("filename.txt", "a") as f:
        f.write("text goes here...")
    

    【讨论】:

      【解决方案2】:

      为此,您必须使用 append mode== "a" 在不删除旧文本的情况下不删除附加文本

      f =open("file.txt","a")
      f.write("Writing in text file old text not deleted ")
      f.close()
      

      【讨论】:

        【解决方案3】:

        f = open('filename.txt', 'a')

        f.writelines('一些文字')

        This wouldn't truncate your text file and will start appending text to your file. 'w' would truncate the old file and start the file as fresh.
        

        【讨论】:

          【解决方案4】:

          参考这个有用的python文档-https://docs.python.org/3/library/functions.html#open,你会发现文件IO的所有不同模式。

          "r" 用于读取,"w" 用于写入,"a" 用于附加,"r+" 用于读取和写入等等......

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-01-11
            • 1970-01-01
            • 2016-08-17
            • 1970-01-01
            • 1970-01-01
            • 2014-09-18
            • 2021-07-15
            相关资源
            最近更新 更多