Python账户管理系统修改金额后控制台查询未展示新余额问题
问题根因
- 内存缓存未同步:在
show_which_account方法里所有账户信息会被一次性读取到全局data字典中缓存,后续存款操作只更新了磁盘上的account.txt文件,没有修改data里对应账户的余额值。查询余额时读取的是data里的旧值,自然不会显示更新后的金额。 - 文件替换逻辑存在漏洞:直接用
filedata.replace(str(credit2), str(amount_e) + '\n')做全局替换,如果有多个账户余额相同,会误修改其他账户的余额。
修复方案
在存款逻辑执行完成后,同步更新data里对应账户的余额值即可解决查询不更新的问题,同时优化文件写入逻辑避免误改其他账户数据,补充要求的禁止透支、负数存取校验,修复后的完整代码如下:
data = {} input_first = "" def show_which_account(): global input_first data.clear() # 切换账户时清空旧数据避免缓存污染 with open("account.txt", encoding='utf-8') as f: print("Which account do you want to use?") for line in f: line = line.strip() if not line: continue account_info = line.split(",") account_number = int(account_info[0]) name = account_info[1].strip() balance = account_info[2].strip() data[account_number] = [name, balance] print(f" [{account_number}] {name}") print(" [0] End") input_first = input(" Your input: ") if input_first.strip() == '0': exit() acc_management() def acc_management(): global input_first input_first = int(input_first) while input_first in data: name2 = data[input_first][0] credit2 = data[input_first][1] print("\n[1] Account Balance \n[2] Deposit \n[3] Withdraw \n[0] Change account") execution = int(input(" Your Input: ")) if execution == 1: # 查询余额直接读缓存,缓存已和文件同步 print(f" The account balance from {name2} is {float(credit2):.2f} $") elif execution == 2: # 存款逻辑,校验负数 while True: try: deposit = float(input(" Your deposit: ")) if deposit < 0: print("Deposit amount cannot be negative, please re-enter") continue break except ValueError: print("Invalid input, please enter a number") new_balance = float(credit2) + deposit # 同步更新内存缓存 data[input_first][1] = str(new_balance) print(f" The account balance of account {name2} is {new_balance:.2f} $") # 优化文件写入逻辑,重写整个文件避免误替换 with open('account.txt', 'w', encoding='utf-8') as file: for acc_num, info in data.items(): file.write(f"{acc_num}, {info[0]}, {info[1]}\n") elif execution == 3: # 取款逻辑,校验负数+透支 while True: try: withdraw = float(input(" Your withdraw amount: ")) if withdraw < 0: print("Withdraw amount cannot be negative, please re-enter") continue if withdraw > float(credit2): print("Insufficient account balance, overdraft is not allowed") continue break except ValueError: print("Invalid input, please enter a number") new_balance = float(credit2) - withdraw data[input_first][1] = str(new_balance) print(f" The account balance of account {name2} is {new_balance:.2f} $") with open('account.txt', 'w', encoding='utf-8') as file: for acc_num, info in data.items(): file.write(f"{acc_num}, {info[0]}, {info[1]}\n") elif execution == 0: show_which_account() break if __name__ == "__main__": show_which_account()
核心修复点
- 存款/取款操作完成后第一时间更新
data里对应账户的余额值,保证内存缓存和磁盘文件数据一致,查询时直接读缓存就能拿到最新值 - 替换原有的全局字符串替换写文件逻辑,改为遍历
data字典重写整个文件,避免多个账户余额相同时的误修改问题 - 补充了取款逻辑,同时实现了禁止透支、禁止负数存取的需求
- 增加了输入合法性校验,避免用户输入非数字内容导致程序崩溃
内容的提问来源于stack exchange,提问作者virat
相关产品推荐
相关产品推荐

