You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何删除、编辑JSON存储字典中的指定患者记录

医院患者信息管理系统单条记录操作改造方案

需求背景

  • 基于现有Python练习项目代码改造,原功能已实现患者基础信息录入、JSON文件存储、全量数据清空
  • 需新增单条患者记录的删除、编辑能力,通过唯一患者编号定位目标记录,操作时不影响其余患者数据
  • 原全量清空逻辑直接覆写整个文件,无法支持精准单条操作,需要补充唯一ID生成、记录定位的相关逻辑

原有代码现存问题

  • 新增患者时未分配唯一标识字段,无法精准定位单条记录
  • 全量清空函数写入内容为[{}],会残留无效空字典对象,不符合列表存储结构
  • 主菜单仅支持读取、新增两个操作,缺少删除、编辑的功能入口
  • 未处理文件首次运行不存在、内容为空时的读取报错问题

改造后完整代码

import json
import os

def read_file(file_name):
    # 兼容首次运行文件不存在/为空的场景
    if not os.path.exists(file_name) or os.path.getsize(file_name) == 0:
        return []
    with open(file_name, 'rt', encoding='utf-8') as obj_arch:
        str_contenido = obj_arch.read()
        if not str_contenido.strip():
            return []
        res = json.loads(str_contenido)
    return res


def save_file(file_name, lista):
    with open(file_name, 'wt', encoding='utf-8') as obj_arch:
        # 增加ensure_ascii=False支持中文正常显示,indent=2格式化输出方便查看
        str_content_to_save = json.dumps(lista, indent=2, ensure_ascii=False)
        print("当前写入文件内容:\n", str_content_to_save)
        obj_arch.write(str_content_to_save)

def clean_json(file_name):
    with open(file_name, 'w', encoding='utf-8') as arc:
        # 修正原逻辑bug,空列表为正确的初始存储结构
        arc.write("[]")

def show_all_patients(lista):
    """打印带唯一编号的全量患者列表,方便用户选择操作目标"""
    if not lista:
        print("当前没有存储任何患者记录")
        return
    print("\n===== 所有患者记录 =====")
    for patient in lista:
        print(f"患者编号:{patient['patient_id']}")
        print(f"姓名:{patient['Name']} {patient['Lastname']}")
        print(f"出生日期:{patient['Date of Birth']}")
        print("------------------------")

# 主程序循环
while True:
    print("\n===== 医院患者信息管理系统 =====")
    print("1 - 查看所有患者记录")
    print("2 - 新增患者信息")
    print("3 - 删除指定患者记录")
    print("4 - 编辑指定患者信息")
    print("5 - 清空所有患者记录")
    print("0 - 退出系统")
    opcion = int(input("请输入你要选择的功能编号:"))

    if opcion == 0:
        print("退出系统")
        break

    # 每次操作前读取文件最新内容,避免数据覆盖
    lista = read_file('prueba_json.json')

    if opcion == 1:
        show_all_patients(lista)

    elif opcion == 2:
        while True:
            print("\n--- 录入新患者信息 ---")
            Name = input("Input name: ")
            Lastname = input("Input lastname: ")
            DateB= input("Input date of birth: ")
            
            # 生成全局唯一患者ID:取现有列表最大ID+1,空列表从1开始编号
            if not lista:
                new_id = 1
            else:
                new_id = max(p['patient_id'] for p in lista) + 1

            lista.append({
                "patient_id": new_id,
                "Name": Name,
                "Lastname": Lastname,
                "Date of Birth": DateB
            })
            save_file('prueba_json.json', lista)
            repeat = input("是否继续添加更多患者?(yes/no): ")
            if repeat.lower() == 'no':
                break

    elif opcion == 3:
        show_all_patients(lista)
        if not lista:
            continue
        target_id = int(input("请输入你要删除的患者编号:"))
        # 遍历匹配目标患者索引
        target_index = -1
        for idx, p in enumerate(lista):
            if p['patient_id'] == target_id:
                target_index = idx
                break
        if target_index == -1:
            print("未找到对应编号的患者,删除失败")
        else:
            deleted_p = lista.pop(target_index)
            save_file('prueba_json.json', lista)
            print(f"已成功删除患者 {deleted_p['Name']} {deleted_p['Lastname']} 的记录")

    elif opcion == 4:
        show_all_patients(lista)
        if not lista:
            continue
        target_id = int(input("请输入你要编辑的患者编号:"))
        target_index = -1
        for idx, p in enumerate(lista):
            if p['patient_id'] == target_id:
                target_index = idx
                break
        if target_index == -1:
            print("未找到对应编号的患者,编辑失败")
        else:
            target_p = lista[target_index]
            print(f"当前正在编辑患者:{target_p['Name']} {target_p['Lastname']},直接回车则保留原有值")
            new_name = input(f"输入新的姓名(原:{target_p['Name']}):")
            new_lastname = input(f"输入新的姓氏(原:{target_p['Lastname']}):")
            new_dob = input(f"输入新的出生日期(原:{target_p['Date of Birth']}):")
            # 仅更新用户输入了新值的字段
            if new_name.strip():
                target_p['Name'] = new_name
            if new_lastname.strip():
                target_p['Lastname'] = new_lastname
            if new_dob.strip():
                target_p['Date of Birth'] = new_dob
            lista[target_index] = target_p
            save_file('prueba_json.json', lista)
            print("患者信息更新成功")

    elif opcion == 5:
        confirm = input("确定要清空所有患者记录吗?操作不可恢复(yes/no): ")
        if confirm.lower() == 'yes':
            clean_json('prueba_json.json')
            print("所有记录已清空")

    else:
        print("输入的功能编号不存在,请重新输入")

核心改造逻辑说明

  • 唯一ID生成规则:每次新增患者时,取当前已存储患者的最大ID值+1作为新患者编号,空列表时从1开始编号,保证每个患者编号全局唯一,不会重复
  • 记录定位逻辑:执行删除/编辑操作前,先打印所有患者的编号和基础信息,接收用户输入的目标编号后遍历列表匹配对应索引,未匹配到则直接返回操作失败提示
  • 删除逻辑:匹配到目标索引后,用列表pop()方法移除对应位置的患者字典,其余元素保持不变,再将修改后的完整列表重新写入JSON文件
  • 编辑逻辑:匹配到目标患者后,逐字段提示用户输入新值,用户直接回车则保留原有字段内容,修改完成后统一保存文件
  • 兼容性处理:完全保留原有代码的读写文件核心逻辑,没有引入额外第三方依赖,同时修复了原代码中文件读取报错、清空逻辑残留无效数据的小问题

内容的提问来源于stack exchange,提问作者newbeat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 10:51:21