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.
The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). Save this answer.
We can keep old content while using write in python by opening the file in append mode. To open a file in append mode, we can use either 'a' or 'a+' as the access mode. The definition of these access modes are as follows: Append Only ('a'): Open the file for writing.
Which mode would you select to write data to a file without losing its existing content? You can do this with the write() method if you open the file with the "w" mode. As you can see, opening a file with the "w" mode and then writing to it replaces the existing content.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With