收入管理系统edit_record函数故障:编辑时新增记录而非更新
修复收入管理系统的edit_record函数问题
问题根源
原函数存在两个核心问题:
- 采用名称匹配,易因重名导致匹配错误;
- 写入文件时使用追加模式而非覆盖模式,导致旧记录保留、新记录重复写入。
修复方案(以Python为例)
修改函数逻辑,以Pancard Number作为唯一匹配标识,读取全部记录后更新目标项,再整体覆盖写入文件:
def edit_record(target_pancard, updated_info): # 读取文件内所有记录 all_records = [] # 假设文件首行为表头,记录格式为:姓名,收入金额,Pancard号,备注 with open("income_records.txt", "r") as f: # 保留表头 header = f.readline().strip() all_records.append(header) for line in f: record = line.strip().split(",") # 匹配目标Pancard号(假设为第3个字段,索引2,需根据实际结构调整) if record[2] == target_pancard: # 替换为更新后的数据,保持字段顺序一致 updated_record = [ updated_info["name"], updated_info["income"], target_pancard, updated_info["remark"] ] all_records.append(",".join(updated_record)) else: # 非目标记录直接保留 all_records.append(",".join(record)) # 覆盖写入文件,替换原内容 with open("income_records.txt", "w") as f: f.write("\n".join(all_records))
关键注意事项
- 确认Pancard Number在记录中的字段位置,根据实际数据结构调整索引;
- 若采用JSON等其他格式存储记录,逻辑一致:读取所有记录到内存,找到匹配项修改后重新写入;
- 操作前建议备份数据,避免写入异常导致数据丢失。
内容的提问来源于stack exchange,提问作者Sudhanshu Kumar
相关产品推荐
相关产品推荐

