Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Open a txt file without clearing everything in it?

Tags:

python

io

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.

like image 254
Takkun Avatar asked Jun 13 '11 18:06

Takkun


People also ask

How do I stop a file overwriting in Python?

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.

How do you write a file without deleting it in Python?

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?

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.


1 Answers

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.

like image 193
Josh Lee Avatar answered Oct 21 '22 13:10

Josh Lee