Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CSV Overwrite

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()
like image 734
Robert Birch Avatar asked Dec 21 '13 08:12

Robert Birch


1 Answers

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.

like image 54
falsetru Avatar answered Nov 06 '22 03:11

falsetru