我正在尝试编写此代码,以便一旦结束,之前的答案将被保存,代码可以再次运行,而不会覆盖旧的答案.我将how,why和scale_of_ten变量转换为’with open’部分,并且我已经取得了一些成功,代码能够在文件执行的次数上工作,但每次执行时,旧的答案都会被覆盖.我如何编写代码,以便在获得新答案时保存旧答案?
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()
解决方法:
使用w模式,open
会截断文件.使用(追加)模式.
....
with open ('happy.csv', 'ab') as f:
# ^
....
顺便说一句,如果你使用with语句,则不需要f.close().