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