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

Python开发电话本:从文本文件删除指定手机号并保存的方法求助

解决思路及修改后的代码

要把修改后的号码列表保存回原文件,核心是将内存中修改后的列表重新转换为符合原格式的字符串,再写入文件,具体步骤和修改后的代码如下:

关键步骤

  • 删除目标号码后,把内存中的号码列表重新拼接成逗号分隔的字符串
  • 以写入模式('w')打开原文件,将拼接后的字符串写入,覆盖原内容
  • 处理边界情况:比如原文件末尾的逗号导致的空字符串、删除后列表为空的场景,避免生成无效格式

修改后的完整函数

def DeleteNumbers(number):
    target_num = str(number)
    print(f"Deleting {target_num} from the list...")
    phonebook_path = "phonebook.txt"  # 替换为你的实际文件路径
    try:
        with open(phonebook_path, 'r') as phonebook_file:
            all_numbers_str = phonebook_file.read()
    except FileNotFoundError:
        print("Oops! File not found!!!")
        return  # 文件不存在直接返回,避免后续报错
    
    all_numbers = all_numbers_str.split(",")
    # 清理拆分后可能出现的空字符串(比如原文件末尾逗号导致的)
    all_numbers = [num for num in all_numbers if num.strip()]
    
    if target_num in all_numbers:
        all_numbers.remove(target_num)
        # 重新拼接成无多余逗号的字符串
        updated_numbers_str = ",".join(all_numbers)
        # 写入文件覆盖原内容
        with open(phonebook_path, 'w') as phonebook_file:
            phonebook_file.write(updated_numbers_str)
        print("The number has been deleted successfully :)")
    else:
        print(False)

额外说明

  • 新增phonebook_path变量明确文件路径,避免依赖全局变量
  • 清理拆分后空字符串,防止误判或生成无效格式
  • 用join方法拼接列表,确保输出字符串格式规范,无多余逗号
  • 全程用with语句管理文件,自动释放资源,避免文件句柄泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:50:04