Python Open a txt file without clearing everything in it?

后端 未结 4 1991
孤城傲影
孤城傲影 2020-12-07 02:38
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         


        
相关标签:
4条回答
  • 2020-12-07 02:56

    You need to open it in append mode

    file = io.open('spam.txt', 'a')
    
    0 讨论(0)
  • 2020-12-07 03:00

    Change 'w' to 'a', for append mode. But you really ought to just keep the file open and write to it when you need it. If you are repeating yourself, use the logging module.

    0 讨论(0)
  • 2020-12-07 03:05
    file = io.open('spam.txt', 'a')
    

    Use mode 'a' for Append.

    0 讨论(0)
  • 2020-12-07 03:13
    file = io.open('spam.txt', 'a') 
    file.write(u'Spam and eggs!\n') 
    file.close()
    

    The w(rite) mode truncates a file, the a(ppend) mode adds to current content.

    0 讨论(0)
提交回复
热议问题