我的任务是在文本文件中记录ATM程序的事务。每次存款或取款后,您必须使用交易类型,存入/取出金额和更新余额更新文件。我能够获取文本文件以打印出当前余额,但仅限一次存款/取款。此外,当程序运行时,它应该打开包含事务的文件并找到帐户的当前余额,但每次运行程序时,新文本只会替换旧文本。 这是我的代码:
balancefile=open("balancefile.txt", "w")
balancefile.write("Starting balance is $10000 \n")
USER_BALANCE=10000
name=input("What is your name? ")
print(name +"," + " " + "Your current balance is: $" + str(USER_BALANCE))
while True:
answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
if answer=="deposit" or answer== "Deposit":
x= input("How much would you like to deposit? ")
USER_BALANCE += float(x)
print (name + "," + " " + "Your new balance is: $" + str(USER_BALANCE))
balancefile.write("You have deposited an amount of $" + x + "." + " " + "Current balance is $" + str(USER_BALANCE) +"\n")
continue
elif answer== "withdraw" or answer== "Withdraw":
y= input("How much would you like to withdraw? ")
if float (y)<=USER_BALANCE:
USER_BALANCE -= float(y)
print (name + "," + " " + "Your new balance is: $" + str(USER_BALANCE))
balancefile.write("You withdrew an amount of $" + y + "." + " " + "Current balance is $" + str(USER_BALANCE) + "\n")
continue
else:
print ("Cannot be done. You have insufficient funds.")
elif answer== "check balance" or answer== "Check Balance":
print ("$" + str(USER_BALANCE))
elif answer== "exit" or answer== "Exit":
print ("Goodbye!")
balancefile.close()
break
else:
print ("I'm sorry, that is not an option")
请帮忙!为了澄清,帐户中的原始金额是10,000美元,但您应该能够在退出文本文件中的最后更新余额后重新输入程序。
答案 0 :(得分:0)
作为the commenters have noted,文件模式'w'
将截断文件proir进行写入,'a'
将打开一个文件进行追加。这将进一步详细描述in the Python documentation。