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

如何实现基于ID或姓名删除文本文件中的学生记录?

学生记录删除功能代码完善思路

我有一个存储学生ID、姓名及其他属性的txt文件,需要实现让用户仅通过输入学生ID或姓名即可删除对应学生记录的功能。下面是现有Python代码和数据示例,寻求完善思路:

数据示例

单条学生记录示例:['102', 'Michael jackson', '3', '54', '30', '84']
文件表头:ID Name

现有代码

def getlist():
    fp = open("student.txt", "r")
    list = fp.readlines()
    for i in range(len(list)):
        list[i] = list[i].split(";")
    return list

print("removing Students from the class based on")
print("1-ID\t2-Student Name")
fp=open("student.txt","r")

list = getlist()
c=int(input("Enter your choice:"))
if(c==1):
    a=int(input("Enter the ID to remove:"))
    for i in range(1,len(list)):
            if a==int(list[i][0]):
                list.remove(list[i])
else:
    b=input("Enter the Student name to remove")
    print("Records found under the name"+"("+b+")")
    for i in range(len(list)):
        if b==list[i][1]:
            print(list[i],end=" ")
            print("\n")

    ####this is for students with the same name
    z=int(input("Please select which record ID to remove:"))    
    
    for i in range(1,len(list)):
        #print(i)
        if z==int(list[i][0]):
            list.remove(list[i])
            break

具体完善方向

1. 文件操作规范优化

  • 用with语句自动管理文件资源,避免忘记关闭文件导致的资源泄漏,同时简化代码。重构getlist函数:
    def getlist():
        with open("student.txt", "r", encoding="utf-8") as fp:
            lines = fp.readlines()
        student_list = []
        for line in lines:
            # 去除换行符后拆分,避免拆分结果带多余换行
            student_info = line.strip().split(";")
            student_list.append(student_info)
        return student_list
    
  • 直接删除原代码中多余的fp=open("student.txt","r"),因为getlist已经完成了文件读取操作。

2. 修复删除逻辑的索引Bug

原代码遍历列表时直接调用list.remove(list[i])会导致索引偏移:删除元素后后续元素前移,下一次循环会跳过一个元素。可以通过先收集待删除索引再倒序删除的方式解决:

# 按ID删除的优化示例
if c == 1:
    target_id = input("请输入要删除的ID:")
    remove_indices = []
    # 从索引1开始遍历,跳过表头行
    for idx, student in enumerate(list[1:], start=1):
        if student[0].strip() == target_id:
            remove_indices.append(idx)
    # 倒序删除,避免索引错乱
    for idx in reversed(remove_indices):
        del list[idx]
    # 给出明确操作反馈
    if remove_indices:
        print(f"已成功删除ID为{target_id}的学生记录")
    else:
        print(f"未找到ID为{target_id}的学生记录")

3. 同名学生处理逻辑优化

  • 增加无匹配记录的判断:如果输入姓名后找不到对应记录,直接提示用户,避免后续无效操作。
  • 优化匹配记录的展示格式,让用户清晰区分不同记录:
else:
    target_name = input("请输入要删除的学生姓名:")
    matched_records = []
    for idx, student in enumerate(list[1:], start=1):
        if student[1].strip() == target_name:
            matched_records.append((idx, student))
    
    if not matched_records:
        print(f"未找到姓名为{target_name}的学生记录")
    else:
        print(f"找到以下姓名为{target_name}的记录:")
        for idx, student in matched_records:
            print(f"序号:{idx} | ID:{student[0]} | 姓名:{student[1]}")
        
        # 单条记录直接确认删除,减少用户操作
        if len(matched_records) == 1:
            confirm = input("仅找到一条记录,是否删除?(y/n):")
            if confirm.lower() == 'y':
                del list[matched_records[0][0]]
                print("已成功删除该记录")
        else:
            target_del_id = input("请输入要删除的记录ID:")
            for idx, student in matched_records:
                if student[0].strip() == target_del_id:
                    del list[idx]
                    print(f"已成功删除ID为{target_del_id}的记录")
                    break
            else:
                print(f"未找到ID为{target_del_id}的记录")

4. 输入合法性校验

  • 对用户输入的选择(1/2)增加校验,避免非整数或无效选项报错:
while True:
    try:
        c = int(input("请输入选择(1-ID/2-姓名):"))
        if c in (1, 2):
            break
        else:
            print("请输入有效的选项:1或2")
    except ValueError:
        print("请输入数字格式的选项")
  • 对ID输入增加数字校验,避免非数字输入导致类型转换错误。

5. 补充文件写入逻辑

原代码仅修改了内存中的列表,没有将修改后的内容写回文件,需要添加写入逻辑:

# 所有修改完成后,将列表写回文件
with open("student.txt", "w", encoding="utf-8") as fp:
    for student in list:
        fp.write(";".join(student) + "\n")

6. 用户体验优化

  • 所有操作完成后给出明确的结果提示,让用户清楚操作是否成功。
  • 全程保留文件表头行,避免误删表头导致文件格式混乱。

内容的提问来源于stack exchange,提问作者Sal The great

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:30:51