简体   繁体   English

Python CSV覆盖

[英]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,why和scale_of_ten变量转换为'with open'部分,并且我已经取得了一些成功,代码能够在文件执行的次数上工作,但每次执行时,旧的答案都会被覆盖。 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. 使用w模式, open截断文件。 Use a (append) mode. 使用a (追加)模式。

....

with open ('happy.csv', 'ab') as f:
    #                    ^
    ....

BTW, f.close() is not needed if you use with statement. 顺便说一句,如果你使用with语句,则f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM