Jessi Jessi - 4 months ago 8
Python Question

save the user input to existing text file everytime running the script python?

I'm trying to save the user input into one text file(I want to keep the record for a month).

But I'm not sure how to keep the old user input because every time I re-run the script new user input is automatically written on old-user input.

Is there any way to keep all the records regardless of running the script?

This is a simple example.

When I run the script once, I get the following result in output textile,

2.5 2015-07-30
7 2015-07-30
1 2015-07-30
4 2015-07-30
5 2015-07-30
8.9 2015-07-30


but when I re-run the script, the above data is all being written by new user input. How can I make it so that my output text file maintains all the record regardless of running the script?
This is my desired look of my output text file

2.5 2015-07-30
7 2015-07-30
1 2015-07-30
4 2015-07-30
5 2015-07-30
8.9 2015-07-30
4 2015-07-31
7 2015-07-31
2.4 2015-07-31
5 2015-07-31
1 2015-07-31


and this is the code that I've tried so far.

import datetime

with open("output.txt", 'w') as textfile:
while True:
input = raw_input("Enter: ")
if input == 'done':
break
textfile.write(input+'\t'+ datetime.datetime.now().strftime("20%y-%m-%d")+'\n')

Answer

You need to open the file in append mode to preserve the data already in the file.

'a' opens the file for appending.

'a+' opens the file for appending and creates the file if it does not exist.

import datetime

with open("output.txt", 'a+') as textfile:
    while True:
        input = raw_input("Enter: ")
        if input == 'done':
            break
        textfile.write(input+'\t'+ datetime.datetime.now().strftime("20%y-%m-%d")+'\n')