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

Python入门通讯录优化:实现本地txt文件持久化存储联系人功能需求

实现方案

不需要复杂数据库,用普通本地文本文件即可实现持久化存储,实现逻辑如下:

  • 程序启动时自动读取本地联系人存储文件,逐行解析后加载到字典中
  • 每次执行新增、删除联系人操作后,自动将最新的联系人数据写入文件覆盖旧内容
  • 兼容首次运行无存储文件的场景,不会报错
优化后完整代码
import os

# 约定联系人存储文件路径
CONTACT_FILE = "contacts.txt"
contact_book = {}

def save_contacts():
    """将当前通讯录数据保存到本地文件"""
    with open(CONTACT_FILE, 'w', encoding='utf-8') as f:
        for name, number in contact_book.items():
            f.write(f"{name},{number}\n")

# 程序启动时加载已有联系人
if os.path.exists(CONTACT_FILE):
    with open(CONTACT_FILE, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            # 按逗号分割,最多分割1次,避免手机号里有逗号出问题
            name, number = line.split(',', 1)
            contact_book[name] = number

while True: 
    user_choice = input("请选择操作: \n [C] - 新建联系人 \n [A] - 查看所有联系人" 
                        "\n [S] - 搜索联系人 \n [D] - 删除联系人 \n [X] - 退出 \n").upper()
    
    if user_choice == "C":
        contact_name = input("请输入联系人姓名:")
        contact_number = input("请输入联系人手机号:")
        contact_book[contact_name] = contact_number
        save_contacts()
        print("联系人创建成功")
        
    elif user_choice == "A": 
        if not contact_book:
            print("当前通讯录为空")
            continue
        for name, number in contact_book.items():
            print(f'姓名 -> {name} 手机号 -> {number}')
    
    elif user_choice == "S":
        search_name = input("请输入要搜索的联系人姓名:")
        if search_name in contact_book:
            print(f'找到联系人:{search_name},手机号为 {contact_book[search_name]}')
        else: 
            print(f"{search_name} 不存在于通讯录中")
    
    elif user_choice == "D":
        contact_to_delete = input("请输入要删除的联系人姓名:")
        if contact_to_delete in contact_book:
            contact_book.pop(contact_to_delete)
            save_contacts()
            print(f"{contact_to_delete} 已删除")
        else:
            print(f"{contact_to_delete} 不存在于通讯录中")
    
    elif user_choice == "X":
        # 退出前再保存一次,兜底避免数据丢失
        save_contacts()
        break
优化说明
  • 新增持久化存储功能:所有联系人会保存在程序同级目录的contacts.txt文件中,重启程序自动加载,原有的搜索、删除、查看功能完全兼容
  • 修复原代码bug:原搜索功能中取手机号错误调用了contact_book.get(contact_name),实际应该取搜索变量search_name,已修正
  • 优化输入输出提示:补充了所有输入场景的提示文字,避免用户不知道要输入什么内容,同时新增了空通讯录的友好提示
  • 优化逻辑判断:将原有的多个并行if改为elif,避免无效判断,同时写入文件时增加了最大分割次数限制,避免特殊字符导致解析错误
  • 新增异常兼容:首次运行无存储文件时不会报错,会自动创建空通讯录,首次操作后自动生成存储文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:36:08