【问题标题】:Python Open a txt file without clearing everything in it?Python 打开一个 txt 文件而不清除其中的所有内容?
【发布时间】:2011-09-14 03:09:16
【问题描述】:
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()

....(Somewhere else in the code)

file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()

我想知道如何保存可以写入的 log.txt 文件? 我希望能够打开一个 txt 文件,写入它,然后能够稍后打开它,并且之前写入的内容仍然存在。

【问题讨论】:

    标签: python io


    【解决方案1】:

    'w' 更改为'a',对应append mode。但是你真的应该保持文件打开并在需要时写入它。如果您重复自己,请使用logging 模块。

    【讨论】:

      【解决方案2】:
      file = io.open('spam.txt', 'a') 
      file.write(u'Spam and eggs!\n') 
      file.close()
      

      w(rite) 模式截断文件,a(pend) 模式添加到当前内容。

      【讨论】:

        【解决方案3】:
        file = io.open('spam.txt', 'a')
        

        使用模式“a”进行追加。

        【讨论】:

          【解决方案4】:

          你需要以追加模式打开它

          file = io.open('spam.txt', 'a')
          

          【讨论】:

            猜你喜欢
            • 2015-11-26
            • 1970-01-01
            • 1970-01-01
            • 2020-03-22
            • 2020-07-19
            • 2023-04-07
            • 2018-07-14
            • 1970-01-01
            • 2022-06-15
            相关资源
            最近更新 更多