Python简单PiggyBank计划

时间:2015-01-30 21:13:05

标签: file python-3.x input output converter

这是我的Python程序,我遇到了一些问题:

- - 编码:cp1252 - -

from time import gmtime, strftime
print("Welcome to the PiggyBank version 1.")
num_write = int(input("How much money would you like to store in your PiggyBank?"))
f = open("PiggyBanks_Records.txt", "w")
current_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())

convert_1 = str(current_time)
convert_2 = str(int(num_write))
add_1 = ("\n" + convert_1 + "   £" + convert_2)
add_2 = ("\n" + add_1) #Tried to make it so new line is added every time the program is run
final_record = str(add_2)

print("Final file written to the PiggyBank: " + final_record)
#Write to File
f.write(final_record)
f.close()

现在,只要程序写入文件,它就会覆盖。我希望保留,就像增加的数量的历史。如果任何人都可以提供帮助,那么需要写入.txt文件的字符串会下降一行,并且基本上会一直持续下去。我也对如何缩短此代码提出任何建议。

2 个答案:

答案 0 :(得分:0)

您需要使用append模式打开文件:

f = open("PiggyBanks_Records.txt", "a")

答案 1 :(得分:0)

使用open的'w'write选项会自动查找指定的文件,如果已存在(可以阅读here),则删除其内容,如果不存在则创建。使用“a”代替添加/附加到文件。