7
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()

I was wondering how I can keep a log.txt file that I can write to? I want to be able to open a txt file, write to it, then be able to open it later and have the contents of the previous write still be there.

martineau
  • 119,623
  • 25
  • 170
  • 301
Takkun
  • 8,119
  • 13
  • 38
  • 41

4 Answers4

12

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.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
1
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.

gnur
  • 4,671
  • 2
  • 20
  • 33
0
file = io.open('spam.txt', 'a')

Use mode 'a' for Append.

George Cummins
  • 28,485
  • 8
  • 71
  • 90
0

You need to open it in append mode

file = io.open('spam.txt', 'a')
dfb
  • 13,133
  • 2
  • 31
  • 52