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

如何在Python程序中访问students.txt内指定学生的详细信息?

解决方案

嘿,我来帮你搞定这个问题!要让show_student()函数能展示指定学生的详细信息,我们得调整它的逻辑,从文件里定位到目标学生的条目,再把身份证号和性别信息提取出来。下面是具体的修改思路和完整代码:

修改思路

  • 精准匹配学生条目:文件里每个学生的信息都是以姓名:开头,后面跟着两行分别是身份证号和性别。我们可以逐行读取文件,找到匹配的姓名行后,直接读取接下来的两行信息。
  • 大小写兼容:不管你输入的姓名是大写还是小写,都能匹配到文件里的条目(比如输入Michael Jackson和michael jackson都能找到同一个学生)。
  • 异常情况处理:如果遍历完整个文件都没找到目标学生,还是会提示“Student not exists.”,同时也会处理文件内容不完整的情况(比如某个学生的信息缺失)。

修改后的完整代码

import csv
import sys
import pathlib

file_path = pathlib.Path("students.txt")
if not file_path.exists():
    # 如果文件不存在,直接创建空文件
    with open("students.txt", "w") as file:
        pass

def login():
    username = input("Username: ")
    password = input("Password: ")
    if username == "a" and password == "b":
        menu()
    else:
        print("Please try again.")
        login()

def menu():
    print("*" * 20 + " Main Menu " + "*" * 20)
    print(" " * 20 + "A: Register student" + " " * 20)
    print(" " * 20 + "B: Show students" + " " * 20)
    print(" " * 20 + "C: Show specific student" + " " * 20)
    print(" " * 20 + "D: Quit" + " " * 20)
    print("*" * 20 + " Main Menu " + "*" * 20)
    operation = input("Enter operation: ")
    if operation.strip().lower() == "a":
        register_student()
    elif operation.strip().lower() == "b":
        show_students()
    elif operation.strip().lower() == "c":
        show_student()
    elif operation.strip().lower() == "d":
        sys.exit()
    else:
        print("Invalid operation.")
        menu()

def register_student():
    student_civil_id = input("Student id: ")
    student_first = input("Student first name: ")
    student_last = input("Student last name: ")
    student_gender = input("Student gender: ")
    student_full = student_first + " " + student_last
    # 优化写入格式,每个学生条目之间加空行分隔,方便后续读取
    with open("students.txt", "a+") as studentInfo:
        studentInfo.seek(0)
        # 如果文件已有内容,先写一个空行分隔
        if studentInfo.read():
            studentInfo.write("\n\n")
        # 写入学生信息,格式更整齐
        studentInfo.write(f"{student_full}:\n Civil id: {student_civil_id}\n Gender: {student_gender}")
    print("Student has been registered.")

def show_students():
    with open("students.txt") as studentInfo:
        content = studentInfo.read()
        if content:
            print(content)
        else:
            print("No students registered yet.")

def show_student():
    student_name = input("Student name: ").strip()
    found = False
    with open("students.txt") as studentInfo:
        lines = studentInfo.readlines()
        # 逐行遍历寻找匹配的学生
        for i in range(len(lines)):
            line = lines[i].strip()
            # 检查当前行是否是学生姓名行(格式为「姓名:」)
            if line.endswith(":") and line[:-1].strip().lower() == student_name.lower():
                found = True
                # 提取身份证号,处理可能的索引越界
                civil_id = lines[i+1].strip().replace("Civil id: ", "") if i + 1 < len(lines) else "Not found"
                # 提取性别,同样处理索引越界
                gender = lines[i+2].strip().replace("Gender: ", "") if i + 2 < len(lines) else "Not found"
                # 输出详细信息
                print("\nStudent Details:")
                print(f"Name: {line[:-1].strip()}")
                print(f"Civil id: {civil_id}")
                print(f"Gender: {gender}")
                break  # 找到后直接退出循环,不用继续遍历
    if not found:
        print("Student not exists.")

login()

关键修改点说明

  1. 文件初始化优化:原代码用a+创建文件,这里改成w直接创建空文件,逻辑更直观。
  2. 注册函数格式优化:注册新学生时,会先检查文件是否为空,不为空就加个空行分隔,让每个学生的信息块更独立,后续读取更方便。
  3. show_student()函数彻底重写:
    • 不再只是检查姓名是否存在,而是逐行定位到目标学生的姓名行。
    • 提取后续两行的身份证和性别信息,还考虑了文件内容不完整的情况(比如某个学生的信息缺失某一行)。
    • 找到学生后直接展示详细信息,未找到则提示不存在。

这样修改之后,你输入学生姓名就能直接看到他的完整信息啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:22:36