7

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()
1
  • 3
    If you're already using with, no need to close the file again. Commented Dec 21, 2013 at 8:37

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So I just get rid f.close() and change 'wb' to 'ab'?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.