I'm trying to write this code so that once it ends the previous answers are saved and the code could be run again without the old answers being overwritten. I moved the how, why and scale_of_ten variables into 'with open' section and I had some success with the code being able to work for the amount of times the files was executed, but each time it was executed the old answers were overwritten. How would I write the code so that it saves the old answers while it takes in new answers?
import csv
import datetime
# imports modules
now = datetime.datetime.now()
# define current time when file is executed
how = str(raw_input("How are you doing?"))
why = str(raw_input("Why do you feel that way?"))
scale_of_ten = int(raw_input("On a scale of 1-10. With 10 being happy and 1 being sad. How happy are you?"))
#creates variables for csv file
x = [now.strftime("%Y-%m-%d %H:%M"),how,why,scale_of_ten]
# creates list for variables to be written in
with open ('happy.csv','wb') as f:
wtr = csv.writer(f)
wtr.writerow(x)
wtr.writerow(x)
f.close()
With w
mode, open
truncates the file. Use a
(append) mode.
....
with open ('happy.csv', 'ab') as f:
# ^
....
BTW, f.close()
is not needed if you use with
statement.
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