【发布时间】:2014-01-10 02:39:52
【问题描述】:
我正在尝试编写此代码,以便在它结束后保存以前的答案,并且可以再次运行代码而不会覆盖旧答案。我将 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()
【问题讨论】:
-
如果您已经在使用
with,则无需再次关闭文件。