如何在Python中通过.txt文件关联账户存储数据?附账户金额存取需求
自定义TXT格式账户金额管理方案
针对你要的这种每行交替账户名、金额的TXT格式,直接写简单的读写函数就能搞定,也顺便给你补下之前json用法的问题:
1. 读取指定账户的金额
读取文件时把所有有效行存成列表,遍历找到目标账户后,下一行就是对应金额:
def get_balance(account_name, file_path="accounts.txt"): try: with open(file_path, "r") as f: # 过滤空行,避免格式问题 lines = [line.strip() for line in f if line.strip()] # 按"账户-金额"的组遍历,步长设为2 for i in range(0, len(lines), 2): if lines[i] == account_name: return float(lines[i+1]) return None # 找不到账户返回None except FileNotFoundError: return None # 文件不存在返回None
用法示例:
balance = get_balance("account1") if balance: print(f"account1余额:{balance}") else: print("账户不存在或文件未找到")
2. 更新/新增账户金额
先读取现有内容,修改后重新写入,支持更新已有账户或新增账户:
def update_balance(account_name, new_balance, file_path="accounts.txt"): lines = [] # 读取现有内容(文件不存在就跳过) try: with open(file_path, "r") as f: lines = [line.strip() for line in f if line.strip()] except FileNotFoundError: pass updated = False # 遍历更新已有账户 for i in range(0, len(lines), 2): if lines[i] == account_name: lines[i+1] = str(new_balance) updated = True break # 没找到账户就新增 if not updated: lines.append(account_name) lines.append(str(new_balance)) # 写入文件 with open(file_path, "w") as f: f.write("\n".join(lines))
用法示例:
# 更新account1余额为1500 update_balance("account1", 1500) # 新增account3,余额800 update_balance("account3", 800)
补充:你提到的json用法问题
其实json更适合做键值对存储,读取后直接通过键名就能取金额,之前没找到方法可能是搞混了dump/load和dumps/loads:
import json # 写入json文件 accounts = {"account1":1000, "account2":129} with open("accounts.json", "w") as f: json.dump(accounts, f) # 读取指定账户金额 with open("accounts.json", "r") as f: accounts = json.load(f) print(accounts.get("account1")) # 直接拿到1000
dump/load是直接和文件交互,dumps/loads是处理字符串,用对方法就能轻松获取指定账户的金额。
内容的提问来源于stack exchange,提问作者wvzack
相关产品推荐
相关产品推荐

