【问题标题】:Python CSV OverwritePython CSV 覆盖
【发布时间】: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,则无需再次关闭文件。

标签: python csv overwrite


【解决方案1】:

w 模式下,open 会截断文件。使用a(追加)模式。

....

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

顺便说一句,如果您使用with 语句,则不需要f.close()

【讨论】:

  • 所以我只是摆脱 f.close() 并将 'wb' 更改为 'ab'?
猜你喜欢
  • 2021-06-30
  • 2018-06-29
  • 2018-08-27
  • 2020-08-24
  • 2016-12-27
  • 2019-02-20
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
相关资源
最近更新 更多