python editing student information system, python student information management system

Hello everyone, this article will focus on writing the student information management system in python, including data saving and reading. How to write the python student information management system code is something that many people want to figure out. They want to figure out the python student information management system code. You need to know the following things before querying.

Implementing student information management system using Python

This article introduces a simple student information management system, including functions such as administrator login, resetting student passwords, adding, deleting and modifying student information, querying student information, and sorting student results. The system is written in Python and based on console interaction

Implementation ideas

The system is divided into two parts, administrator login and student information management. Can you download weighing software on your mobile phone? Can you download steam on your mobile phone ? When the administrator logs in, the program will ask the user to enter their username and password for identity verification; after passing the verification, they will enter the student information management interface. The student information management interface provides a variety of operation methods, including functions such as resetting student passwords, adding, deleting, and modifying student information, querying student information, and sorting student results.

During the implementation process, we used files to store student information, where each line represents a student's information, and each field is separated by commas. When sorting student scores, we calculate the average score of each student and use it as the basis for sorting.

Code

login interface

# 登录界面
def login():
    print("欢迎使用学生信息管理系统") # 打印欢迎信息
    while True: # 一直循环直到输入正确的角色类型
        role = input("请输入登录角色(1-学生,2-管理员):") # 输入角色类型
        if role == '1': # 如果输入是学生
            student_login() # 转到学生登录函数
            break # 结束循环
        elif role == '2': # 如果输入是管理员
            admin_login() # 转到管理员登录函数
            break # 结束循环
        else:
            print("输入有误,请重新输入") # 提示输入错误,重新输入

Execution effect

Please add image description

student login

# 学生登录
def student_login():
    while True: # 一直循环直到输入正确的账号和密码
        account = input("请输入账号:") # 输入账号
        password = input("请输入密码:") # 输入密码
        with open('xs.txt', 'r', encoding='utf-8') as f: # 打开存放学生信息的文件
            for line in f: # 遍历所有行
                data = line.strip().split() # 分隔每行数据
                姓名 = data[0].split(':')[1].strip() # 获取姓名
                学号 = data[1].split(':')[1].strip() # 获取学号
                账号 = data[2].split(':')[1].strip() # 获取账号
                密码 = data[3].split(':')[1].strip() # 获取密码
                if 账号 == account and 密码 == password: # 如果账号和密码匹配
                    print(f"欢迎登陆,{姓名}同学!") # 打印欢迎信息
                    student_menu(account) # 转到学生菜单函数
                    return # 结束函数
            print("账号或密码错误,请重新输入") # 提示输入错误,重新输入

Execution effect

Please add image description

Student menu

# 学生菜单
def student_menu(account):
    while True: # 一直循环直到选择退出系统或者退回登录界面
        print("""
        ================
            1. 查看所有学生信息
            2. 查询个人信息
            3. 退回登录界面
            0. 退出系统
        ================
        """) # 打印菜单
        choice = input("请输入您的选择:") # 输入选项
        if choice == "1": # 如果输入为 1
            show_all_students() # 转到显示所有学生信息函数
        elif choice == "2": # 如果输入为 2
            show_student_info() # 转到显示个人信息函数
        elif choice == "3": # 如果输入为 3
            login() # 返回登陆
        elif choice == "0": # 如果输入为 0
            print("感谢使用本系统,再见!") # 打印欢送信息
            exit() # 退出程序
        else:
            print("输入有误,请重新输入!") # 提示输入错误,重新输入

Execution effect

Please add image description

Show all student information

# 展示所有学生信息
def show_all_students():
    with open('xinxi.txt', 'r',encoding='utf-8') as f: # 打开存放学生信息的文件
        lines = f.readlines() # 读取所有行
        if len(lines) == 0: # 如果文件为空
            print("暂无学生信息") # 打印提示信息
            return # 结束函数
        header = "{:<6}{:<10}{:<12}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}".format("姓  名", "班   级", "学  号", "Linux", "Python", "C语言", "C++语言", "Java语言", "平均分") # 定义表头格式
        print(header) # 打印表头
        for line in lines: # 遍历每一行数据
            info = line.strip().split(',') # 分隔每行数据
            student_info = "{:<6}{:<10}{:<12}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}".format(info[0], info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8]) # 格式化学生信息
            print(student_info) # 打印学生信息

Execution effect

Please add image description

Query the student information of a single student

# 查询单个学生的学生信息
def show_student_info():
    student_id = input("请输入要查询的学号:") # 输入学号
    with open('xinxi.txt', 'r', encoding='utf-8') as f: # 打开存放学生信息的文件
        found = False # 判断是否找到该学生信息
        for line in f: # 遍历每一行数据
            info = line.strip().split(',') # 分隔每行数据
            if info[2] == student_id: # 如果该行数据中的学号和输入的学号相同
                print(f"姓名:{info[0]}") # 打印姓名
                print(f"班级:{info[1]}") # 打印班级
                print(f"学号:{info[2]}") # 打印学号
                print(f"Linux成绩:{info[3]}") # 打印 Linux 成绩
                print(f"Python成绩:{info[4]}") # 打印 Python 成绩
                print(f"C语言成绩:{info[5]}") # 打印 C 语言成绩
                print(f"C++语言成绩:{info[6]}") # 打印 C++ 语言成绩
                print(f"Java语言成绩:{info[7]}") # 打印 Java 语言成绩
                print(f"平均分:{info[8]}") # 打印平均分
                found = True # 标记为找到
                break # 结束循环
        if not found: # 如果未找到该学生信息
            print("未找到该学号的学生信息") # 提示未找到

Execution effect

Please add image description

Administrator login

# 管理员登录
def admin_login():
    while True: # 一直循环直到输入正确的账号和密码或手动退出
        account = input("请输入账号:") # 输入账号
        password = input("请输入密码:") # 输入密码
        try:
            with open('gly.txt', 'r', encoding='utf-8') as f: # 打开存放管理员信息的文件
                for line in f: # 遍历每一行数据
                    info = line.strip().split(' ') # 分隔每行数据
                    if len(info) != 4: # 如果分割后的数据不是 4 项(即格式不正确)
                        continue # 跳过本次循环
                    # 根据文件内容里的冒号进行处理
                    name = info[0].split(':')[1] # 获取姓名
                    num = info[1].split(':')[1] # 获取工号
                    acc = info[2].split(':')[1] # 获取账号
                    pwd = info[3].split(':')[1] # 获取密码
                    if acc == account and pwd == password: # 如果账号和密码匹配
                        print(f"欢迎登陆,{name}管理员!") # 打印欢迎信息
                        admin_menu() # 转到管理员菜单函数
                        return # 结束函数
                print("账号或密码错误,请重新输入") # 提示输入错误,重新输入
        except IOError: # 捕获文件打开异常
            print("无法打开文件,请检查文件路径和权限") # 提示无法打开文件
            return # 结束函数
        except Exception as e: # 捕获其他异常
            print(f"发生错误:{str(e)}") # 打印错误信息
            return # 结束函数

Execution effect

Please add image description

Administrator menu

# 管理员菜单
def admin_menu():
    while True: # 一直循环直到选择退出程序
        choice = input(
            "请选择操作(1-重置学生账号密码,2-添加学生信息,3-删除学生信息,4-修改学生信息,5-查询学生信息,6-学生成绩排序,0-退出):") # 打印管理员操作菜单,输入选项
        if choice == '1': # 如果选择 1
            reset_password() # 转到重置学生账号密码函数
        elif choice == '2': # 如果选择 2
            add_student() # 转到添加学生信息函数
        elif choice == '3': # 如果选择 3
            delete_student() # 转到删除学生信息函数
        elif choice == '4': # 如果选择 4
            modify_student() # 转到修改学生信息函数
        elif choice == '5': # 如果选择 5
            search_student() # 转到查询学生信息函数
        elif choice == '6': # 如果选择 6
            sort_students() # 转到学生成绩排序函数
        elif choice == '0': # 如果选择 0
            break # 退出循环
        else:
            print("输入有误,请重新输入") # 提示输入错误,重新输入

Execution effect

Please add image description

Reset student account password

# 重置学生账号密码
def reset_password():
    choice = input("请选择操作(1-修改密码,2-删除账号,3-添加账号):") # 打印选项菜单,输入选择
    if choice == '1': # 如果选择 1
        student_id = input("请输入要修改密码的学号:") # 输入要修改密码的学号
        with open('xs.txt', 'r', encoding='utf-8-sig') as f: # 打开存放学生信息的文件
            lines = f.readlines() # 读取所有行数据
            for i in range(len(lines)): # 遍历每一行数据
                line = lines[i].strip() # 去除首尾空格
                info = line.split() # 分隔每行数据
                if len(info) != 4: # 如果分割后的数据不是 4 项(即格式不正确)
                    continue # 跳过本次循环
                name = info[0][3:] # 获取姓名
                sid = info[1][3:] # 获取学号
                account = info[2][3:] # 获取账号
                password = info[3][3:] # 获取密码
                if sid == student_id: # 如果学号匹配
                    print(f"姓名:{name},学号:{sid},账号:{account},密码:{password}") # 打印该学生信息
                    new_password = input("请输入新密码:") # 输入新密码
                    # 修改密码
                    lines[i] = f"姓名:{name} 学号:{sid} 账号:{account} 密码:{new_password}\n"
                    with open('xs.txt', 'w', encoding='utf-8-sig') as f:
                        f.writelines(lines)
                    print("密码修改成功") # 提示密码修改成功
                    break # 结束循环
            else: # 如果未找到该学生信息
                print("未找到该学号的学生信息") # 提示未找到
    elif choice == '2': # 如果选择 2
        student_id = input("请输入要删除账号的学号:") # 输入要删除账号的学号
        with open('xs.txt', 'r', encoding='utf-8-sig') as f: # 打开存放学生信息的文件
            lines = f.readlines() # 读取所有行数据
            for i in range(len(lines)): # 遍历每一行数据
                line = lines[i].strip() # 去除首尾空格
                info = line.split() # 分隔每行数据
                if len(info) != 4: # 如果分割后的数据不是 4 项(即格式不正确)
                    continue # 跳过本次循环
                name = info[0][3:] # 获取姓名
                sid = info[1][3:] # 获取学号
                account = info[2][3:] # 获取账号
                password = info[3][3:] # 获取密码
                if sid == student_id: # 如果学号匹配
                    print(f"姓名:{name},学号:{sid},账号:{account},密码:{password}") # 打印该学生信息
                    # 删除账号
                    del lines[i] # 删除该行数据
                    with open('xs.txt', 'w', encoding='utf-8-sig') as f:
                        f.writelines(lines)
                    print("账号删除成功") # 提示账号删除成功
                    break # 结束循环
            else: # 如果未找到该学生信息
                print("未找到该学号的学生信息") # 提示未找到
    elif choice == '3': # 如果选择 3
        new_sid = input("请输入新的学号:") # 输入新学号
        new_name = input("请输入姓名:") # 输入姓名
        new_account = input("请输入账号:") # 输入账号
        new_password = input("请输入密码:") # 输入密码
        new_line = f"姓名:{new_name} 学号:{new_sid} 账号:{new_account} 密码:{new_password}\\n"
        with open('xs.txt', 'a', encoding='utf-8-sig') as f: # 打开存放学生信息的文件
            f.write(new_line) # 写入新行数据
        print("账号添加成功") # 提示账号添加成功
    else:
        print("输入有误,请重新选择") # 提示选择错误,重新选择操作


Execution effect

Please add image description

Add student information

# 添加学生信息
def add_student():
    # 要求用户输入学生信息(姓名,班级,学号,Linux成绩,Python成绩,C语言成绩,C++语言成绩,Java语言成绩)
    student_info = input("请输入学生信息(姓名,班级,学号,Linux成绩,Python成绩,C语言成绩,C++语言成绩,Java语言成绩):")
    info_list = student_info.split(',') # 将输入的信息按逗号分隔开
    if len(info_list) < 8: # 如果信息项不足8项(即输入不完整)
        print("输入的信息不完整,请重新输入!") # 提示信息不完整
        return
    name, cls, id, linux, python, c, cpp, java = info_list[:8] # 获取各个信息项
    total_score = (int(linux) + int(python) + int(c) + int(cpp) + int(java)) / 5 # 计算平均分
    student_info = f"{name},{cls},{id},{linux},{python},{c},{cpp},{java}" # 构造要写入文件的字符串
    with open('xinxi.txt', 'a', encoding='utf-8') as f: # 打开存放学生信息的文件(以追加方式)
        f.write(f"{student_info},{total_score}\n") # 将学生信息和平均分写入文件
    print(f"学生信息添加成功,平均分为{total_score},平均分已自动填充") # 输出添加成功提示信息

Execution effect

Please add image description

Delete student information

# 删除学生信息
def delete_student():
    student_id = input("请输入要删除信息的学号:")
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for i in range(len(lines)):
            info = lines[i].strip().split(",")
            if info[2] == student_id:
                del lines[i]
                with open('xinxi.txt', 'w', encoding='utf-8') as f:
                    f.writelines(lines)
                print("学生信息删除成功")
                break
        else:
            print("未找到该学号的学生信息")

Execution effect

Please add image description

Modify student information

# 修改学生信息
def modify_student():
    # 输入要修改信息的学号
    student_id = input("请输入要修改信息的学号:")
    # 打开文件并读取所有行
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        # 循环遍历每一行
        for i in range(len(lines)):
            # 分割数据并赋值给变量
            data = lines[i].strip().split(',')
            学生姓名 = data[0]
            班级 = data[1]
            学号 = data[2]
            Linux成绩 = int(data[3])
            Python成绩 = int(data[4])
            C语言成绩 = int(data[5])
            Cpp语言成绩 = int(data[6])
            Java语言成绩 = int(data[7])
            平均分 = float(data[8])
            # 如果学号匹配成功,则进入修改流程
            if 学号 == student_id:
                # 输入新的学生信息
                new_info_str = input(
                    "请按照格式输入新的学生信息(姓名,班级,学号,Linux成绩,Python成绩,C语言成绩,C++语言成绩,Java语言成绩):")
                # 分割新的学生信息并赋值给变量
                new_info = new_info_str.strip().split(',')
                new_学生姓名 = new_info[0]
                new_班级 = new_info[1]
                new_学号 = new_info[2]
                new_Linux成绩 = int(new_info[3])
                new_Python成绩 = int(new_info[4])
                new_C语言成绩 = int(new_info[5])
                new_Cpp语言成绩 = int(new_info[6])
                new_Java语言成绩 = int(new_info[7])
                # 计算新的平均分
                new_平均分 = (new_Linux成绩 + new_Python成绩 + new_C语言成绩 + new_Cpp语言成绩 + new_Java语言成绩) / 5
                # 生成新的一行数据并替换旧的数据
                lines[i] = f"{new_学生姓名},{new_班级},{new_学号},{new_Linux成绩},{new_Python成绩},{new_C语言成绩},{new_Cpp语言成绩},{new_Java语言成绩},{new_平均分}\n"
                # 打开文件并写入新的所有行
                with open('xinxi.txt', 'w', encoding='utf-8') as f:
                    f.writelines(lines)
                # 输出成功信息并结束函数
                print("学生信息修改成功")
                break
        else:
            # 如果未找到该学号的学生信息,则输出失败信息
            print("未找到该学号的学生信息")

Execution effect

Please add image description

Query student information

# 查询学生信息
def search_student():
    # 输入要查询信息的学号
    student_id = input("请输入要查询信息的学号:")
    # 打开文件并逐行读取
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        for line in f:
            # 分割数据并赋值给变量
            data = line.strip().split(',')
            学生姓名 = data[0]
            班级 = data[1]
            学号 = data[2]
            Linux成绩 = data[3]
            Python成绩 = data[4]
            C语言成绩 = data[5]
            Cpp语言成绩 = data[6]
            Java语言成绩 = data[7]
            平均分 = data[8]
            # 如果学号匹配成功,则输出学生信息并结束函数
            if 学号 == student_id:
                print(f"姓名:{学生姓名}")
                print(f"班级:{班级}")
                print(f"学号:{学号}")
                print(f"Linux成绩:{Linux成绩}")
                print(f"Python成绩:{Python成绩}")
                print(f"C语言成绩:{C语言成绩}")
                print(f"C++语言成绩:{Cpp语言成绩}")
                print(f"Java语言成绩:{Java语言成绩}")
                print(f"平均分:{平均分}")
                break
        else:
            # 如果未找到该学号的学生信息,则输出失败信息
            print("未找到该学号的学生信息")

Execution effect

Please add image description

Student performance sorting

# 学生成绩排序
def sort_students():
    # 循环直到用户输入正确选项为止
    while True:
        choice = input("请选择排序方式(1-升序,2-降序):")
        if choice == '1':
            reverse = False
            break
        elif choice == '2':
            reverse = True
            break
        else:
            print("输入有误,请重新选择")
    # 打开文件并读取所有行
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        students = []
        # 循环遍历每一行数据,并将其转化为元组类型加入到 students 列表中
        for line in lines:
            info = line.strip().split(',')
            score_sum = sum(map(float, info[3:]))
            students.append((info[0], info[1], info[2], *info[3:], score_sum))
        # 对 students 列表进行排序
        students.sort(key=lambda x: x[-1], reverse=reverse)
        # 输出表格标题
        print("排序结果如下:")
        print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
              "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")
        print("|{:^8}|{:^15}|{:^10}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|".format(
            "姓名", "班级", "学号", "Linux", "Python", "C语言", "C++语言", "Java语言", "平均分"))
        print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
              "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")
        # 循环遍历每一个排序后的学生信息,并输出到控制台上
        for student in students:
            print("|{:^8}|{:^15}|{:^10}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|".format(
                student[0], student[1], student[2], student[3], student[4], student[5], student[6], student[7], student[8]))
            print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
                  "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")

Execution effect

Please add image description

main function

# 主函数
if __name__ == '__main__':
    # 调用登录函数
    login()

Program design analysis

Function module division

The student performance management system mainly includes the following functional modules:

  1. Student information adding module;
  2. Student information deletion module;
  3. Student information modification module;
  4. Student information query module;
  5. Student performance ranking module;
  6. Student account management module;
  7. Administrator login module;
  8. Administrator operation rights management module;
  9. Administrator account management module.

Therefore, we can divide the entire program into nine parts to implement the above nine functional modules respectively.

Data storage method

In this project, we use text files to store student information, account information, and administrator information. Specifically, we store student information in a file named, each line represents a student's information, including the student's name, class name, student number, and grades of five courses; account information is stored in a file named, Each line represents a student's account information, including student name, student number, account number, and password; the administrator information is stored in a file named. Each line represents an administrator's account information, including administrator account and password. This method is simple and convenient, easy to implement and maintain.xinxi.txt xs.txt gly.txt

Program flow design

The program flow of this project is as follows:

  1. Print out a menu and let the user choose an action to perform;
  2. If the user selects the administrator login operation, the administrator login module is executed, requiring the user to enter the administrator account and password and compare it with the information stored in the file named; if the comparison is successful, the administrator operation permissions can be obtained Administration and administrator account management;gly.txt
  3. According to the user's selection, the corresponding function is called to implement the corresponding function;
  4. The user can perform actions repeatedly until they choose to exit the program.

The specific function implementation and structural design will be introduced in the next section.

Summarize

This project is a simple student performance management system. Through the analysis and implementation of this project, we can master the basic file processing skills, string operation skills, exception handling skills, etc. of the Python language; it also deepens our understanding of process-oriented programming. The ability to understand and apply ideas. These skills and experiences will be very useful in future development work.

Complete code


# 登录界面
def login():
    print("欢迎使用学生信息管理系统")
    while True:
        role = input("请输入登录角色(1-学生,2-管理员):")
        if role == '1':
            student_login()
            break
        elif role == '2':
            admin_login()
            break
        else:
            print("输入有误,请重新输入")


# 学生登录
def student_login():
    while True:
        account = input("请输入账号:")
        password = input("请输入密码:")
        with open('xs.txt', 'r', encoding='utf-8') as f:
            for line in f:
                data = line.strip().split()
                姓名 = data[0].split(':')[1].strip()
                学号 = data[1].split(':')[1].strip()
                账号 = data[2].split(':')[1].strip()
                密码 = data[3].split(':')[1].strip()
                if 账号 == account and 密码 == password:
                    print(f"欢迎登陆,{姓名}同学!")
                    student_menu(account)
                    return
            print("账号或密码错误,请重新输入")




# 学生菜单
def student_menu(account):
    while True:
        print("""
        ================
            1. 查看所有学生信息
            2. 查询个人信息
            3. 退回登录界面
            0. 退出系统
        ================
        """)
        choice = input("请输入您的选择:")
        if choice == "1":
            show_all_students()
        elif choice == "2":
            show_student_info()
        elif choice == "3":
            return
        elif choice == "0":
            print("感谢使用本系统,再见!")
            exit()
        else:
            print("输入有误,请重新输入!")



# 展示所有学生信息
def show_all_students():
    with open('xinxi.txt', 'r',encoding='utf-8') as f:
        lines = f.readlines()
        if len(lines) == 0:
            print("暂无学生信息")
            return
        header = "{:<6}{:<10}{:<12}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}".format("姓  名", "班   级", "学  号", "Linux", "Python", "C语言", "C++语言", "Java语言", "平均分")
        print(header)
        for line in lines:
            info = line.strip().split(',')
            student_info = "{:<6}{:<10}{:<12}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}".format(info[0], info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8])
            print(student_info)



# 查询单个学生的学生信息
def show_student_info():
    student_id = input("请输入要查询的学号:")
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        found = False
        for line in f:
            info = line.strip().split(',')
            if info[2] == student_id:
                print(f"姓名:{info[0]}")
                print(f"班级:{info[1]}")
                print(f"学号:{info[2]}")
                print(f"Linux成绩:{info[3]}")
                print(f"Python成绩:{info[4]}")
                print(f"C语言成绩:{info[5]}")
                print(f"C++语言成绩:{info[6]}")
                print(f"Java语言成绩:{info[7]}")
                print(f"平均分:{info[8]}")
                found = True
                break

        if not found:
            print("未找到该学号的学生信息")



# 管理员登录
def admin_login():
    while True:
        account = input("请输入账号:")
        password = input("请输入密码:")
        try:
            with open('gly.txt', 'r', encoding='utf-8') as f:
                for line in f:
                    info = line.strip().split(' ')
                    if len(info) != 4:
                        continue
                    # 根据文件内容里的冒号进行处理
                    name = info[0].split(':')[1]
                    num = info[1].split(':')[1]
                    acc = info[2].split(':')[1]
                    pwd = info[3].split(':')[1]
                    if acc == account and pwd == password:
                        print(f"欢迎登陆,{name}管理员!")
                        admin_menu()
                        return
                print("账号或密码错误,请重新输入")
        except IOError:
            print("无法打开文件,请检查文件路径和权限")
            return
        except Exception as e:
            print(f"发生错误:{str(e)}")
            return




# 管理员菜单
def admin_menu():
    while True:
        choice = input(
            "请选择操作(1-重置学生账号密码,2-添加学生信息,3-删除学生信息,4-修改学生信息,5-查询学生信息,6-学生成绩排序,0-退出):")
        if choice == '1':
            reset_password()
        elif choice == '2':
            add_student()
        elif choice == '3':
            delete_student()
        elif choice == '4':
            modify_student()
        elif choice == '5':
            search_student()
        elif choice == '6':
            sort_students()
        elif choice == '0':
            break
        else:
            print("输入有误,请重新输入")


# 重置学生账号密码
def reset_password():
    choice = input("请选择操作(1-修改密码,2-删除账号,3-添加账号):")
    if choice == '1':
        student_id = input("请输入要修改密码的学号:")
        with open('xs.txt', 'r', encoding='utf-8-sig') as f:
            lines = f.readlines()
            for i in range(len(lines)):
                line = lines[i].strip()
                info = line.split()
                if len(info) != 4:
                    continue
                name = info[0][3:] # 姓名
                sid = info[1][3:] # 学号
                account = info[2][3:] # 账号
                password = info[3][3:] # 密码
                if sid == student_id:
                    print(f"姓名:{name},学号:{sid},账号:{account},密码:{password}")
                    new_password = input("请输入新密码:")
                    # 修改密码
                    lines[i] = f"姓名:{name} 学号:{sid} 账号:{account} 密码:{new_password}\n"
                    with open('xs.txt', 'w', encoding='utf-8-sig') as f:
                        f.writelines(lines)
                    print("密码修改成功")
                    break
            else:
                print("未找到该学号的学生信息")
    elif choice == '2':
        student_id = input("请输入要删除账号的学号:")
        with open('xs.txt', 'r', encoding='utf-8-sig') as f:
            lines = f.readlines()
            for i in range(len(lines)):
                line = lines[i].strip()
                info = line.split()
                if len(info) != 4:
                    continue
                name = info[0][3:] # 姓名
                sid = info[1][3:] # 学号
                account = info[2][3:] # 账号
                password = info[3][3:] # 密码
                if sid == student_id:
                    print(f"姓名:{name},学号:{sid},账号:{account},密码:{password}")
                    # 删除账号
                    del lines[i]
                    with open('xs.txt', 'w', encoding='utf-8-sig') as f:
                        f.writelines(lines)
                    print("账号删除成功")
                    break
            else:
                print("未找到该学号的学生信息")
    elif choice == '3':
        new_sid = input("请输入新的学号:")
        new_name = input("请输入姓名:")
        new_account = input("请输入账号:")
        new_password = input("请输入密码:")
        new_line = f"姓名:{new_name} 学号:{new_sid} 账号:{new_account} 密码:{new_password}\n"
        with open('xs.txt', 'a', encoding='utf-8-sig') as f:
            f.write(new_line)
        print("账号添加成功")
    else:
        print("输入有误,请重新选择")




# 添加学生信息
def add_student():
    student_info = input("请输入学生信息(姓名,班级,学号,Linux成绩,Python成绩,C语言成绩,C++语言成绩,Java语言成绩):")
    info_list = student_info.split(',')
    if len(info_list) < 8:
        print("输入的信息不完整,请重新输入!")
        return
    name, cls, id, linux, python, c, cpp, java = info_list[:8]
    total_score = (int(linux) + int(python) + int(c) + int(cpp) + int(java)) / 5
    student_info = f"{name},{cls},{id},{linux},{python},{c},{cpp},{java}"
    with open('xinxi.txt', 'a', encoding='utf-8') as f:
        f.write(f"{student_info},{total_score}\n")
    print(f"学生信息添加成功,平均分为{total_score},平均分已自动填充")



# 删除学生信息
def delete_student():
    student_id = input("请输入要删除信息的学号:")
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for i in range(len(lines)):
            info = lines[i].strip().split(",")
            if info[2] == student_id:
                del lines[i]
                with open('xinxi.txt', 'w', encoding='utf-8') as f:
                    f.writelines(lines)
                print("学生信息删除成功")
                break
        else:
            print("未找到该学号的学生信息")


# 修改学生信息
def modify_student():
    student_id = input("请输入要修改信息的学号:")
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for i in range(len(lines)):
            data = lines[i].strip().split(',')
            学生姓名 = data[0]
            班级 = data[1]
            学号 = data[2]
            Linux成绩 = int(data[3])
            Python成绩 = int(data[4])
            C语言成绩 = int(data[5])
            Cpp语言成绩 = int(data[6])
            Java语言成绩 = int(data[7])
            平均分 = float(data[8])
            if 学号 == student_id:
                new_info_str = input(
                    "请按照格式输入新的学生信息(姓名,班级,学号,Linux成绩,Python成绩,C语言成绩,C++语言成绩,Java语言成绩):")
                new_info = new_info_str.strip().split(',')
                new_学生姓名 = new_info[0]
                new_班级 = new_info[1]
                new_学号 = new_info[2]
                new_Linux成绩 = int(new_info[3])
                new_Python成绩 = int(new_info[4])
                new_C语言成绩 = int(new_info[5])
                new_Cpp语言成绩 = int(new_info[6])
                new_Java语言成绩 = int(new_info[7])
                new_平均分 = (new_Linux成绩 + new_Python成绩 + new_C语言成绩 + new_Cpp语言成绩 + new_Java语言成绩) / 5
                lines[i] = f"{new_学生姓名},{new_班级},{new_学号},{new_Linux成绩},{new_Python成绩},{new_C语言成绩},{new_Cpp语言成绩},{new_Java语言成绩},{new_平均分}\n"
                with open('xinxi.txt', 'w', encoding='utf-8') as f:
                    f.writelines(lines)
                print("学生信息修改成功")
                break
        else:
            print("未找到该学号的学生信息")




# 查询学生信息
def search_student():
    student_id = input("请输入要查询信息的学号:")
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        for line in f:
            data = line.strip().split(',')
            学生姓名 = data[0]
            班级 = data[1]
            学号 = data[2]
            Linux成绩 = data[3]
            Python成绩 = data[4]
            C语言成绩 = data[5]
            Cpp语言成绩 = data[6]
            Java语言成绩 = data[7]
            平均分 = data[8]
            if 学号 == student_id:
                print(f"姓名:{学生姓名}")
                print(f"班级:{班级}")
                print(f"学号:{学号}")
                print(f"Linux成绩:{Linux成绩}")
                print(f"Python成绩:{Python成绩}")
                print(f"C语言成绩:{C语言成绩}")
                print(f"C++语言成绩:{Cpp语言成绩}")
                print(f"Java语言成绩:{Java语言成绩}")
                print(f"平均分:{平均分}")
                break
        else:
            print("未找到该学号的学生信息")




# 学生成绩排序
def sort_students():
    while True:
        choice = input("请选择排序方式(1-升序,2-降序):")
        if choice == '1':
            reverse = False
            break
        elif choice == '2':
            reverse = True
            break
        else:
            print("输入有误,请重新选择")
    with open('xinxi.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        students = []
        for line in lines:
            info = line.strip().split(',')
            score_sum = sum(map(float, info[3:]))
            students.append((info[0], info[1], info[2], *info[3:], score_sum))
        students.sort(key=lambda x: x[-1], reverse=reverse)
        print("排序结果如下:")
        print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
              "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")
        print("|{:^8}|{:^15}|{:^10}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|".format(
            "姓名", "班级", "学号", "Linux", "Python", "C语言", "C++语言", "Java语言", "平均分"))
        print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
              "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")
        for student in students:
            print("|{:^8}|{:^15}|{:^10}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|".format(
                student[0], student[1], student[2], student[3], student[4], student[5], student[6], student[7], student[8]))
            print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
                  "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")


# 主函数
if __name__ == '__main__':
    login()

Guess you like

Origin blog.csdn.net/chatgpt001/article/details/132969139