Python 简单的存钱罐程序

Python Simple PiggyBank Program

这是我的 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 文件的字符串会下降一行,并且基本上会一直持续下去。我也愿意接受有关如何缩短此代码的任何建议。

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

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

使用带有 open 的 'w' 写入选项会自动查找指定的文件,如果它已经存在则删除其内容(您可以阅读有关 here 的内容)或者如果不存在则创建它'吨。使用 'a' 来添加/附加到文件。