python之学生信息管理系统(控制台程序)

一、文件夹结构

在这里插入图片描述

二、相关说明

1、系统开发环境

windows10系统,python3.6,开放工具ptcharm2018

2、相关库

python内置模块os和re

三、系统功能结构

包括6大模块
录入学生信息模块、删除学生模块,修改学生模块,查找学生模块,排序学生模块,查询、统计学生模块。

四、相关代码

# _*_ coding:utf-8   _*_
import re, os
def main():
    ctrl = True   # 标记是否退出系统
    while(ctrl):
        menu()    # 显示菜单
        option = input("请选择")   # 选择菜单项
        option_str = re.sub("\D", "", option)
        if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
            option_int = int(option_str)
            if option_int == 0:
                print("你已退出学生信息管理系统!")
                ctrl = False
            elif option_int == 1:    # 录入学生信息
                insert()
            elif option_int == 2:    # 查找学生信息
                search()
            elif option_int == 3:    # 删除学生信息
                delete()
            elif option_int == 4:    # 修改学生信息
                modify()
            elif option_int == 5:    # 排序学生信息
                sort()
            elif option_int == 6:    # 统计学生信息总数
                total()
            elif option_int == 7:    # 显示所有学生信息
                show()


def menu():
    # 输出菜单
    print('''
    ╔———————学生信息管理系统————————╗
    │                                              │
    │   =============== 功能菜单 ===============   │
    │                                              │
    │   1 录入学生信息                             │
    │   2 查找学生信息                             │
    │   3 删除学生信息                             │
    │   4 修改学生信息                             │
    │   5 排序                                     │
    │   6 统计学生总人数                           │
    │   7 显示所有学生信息                         │
    │   0 退出系统                                 │
    │  ==========================================  │
    │  说明:通过数字或↑↓方向键选择菜单          │
    ╚———————————————————————╝
    ''')


def save(student):
    try:
        student_txt = open('student.txt', "a")   # 追加模式打开
    except Exception as e:
        student_txt = open('student.txt',"w")    # 文件不存在,创建文件打开
    for info in student:
        student_txt.write(str(info) + "\n")     # 按行存储,添加换行符
    student_txt.close()


def insert():
    studentList = [] # 添加保存学生信息的列表
    mark = True      # 是否继续
    while mark:
        id = input("请输入IP(如317XXXXX1):")
        if not id:    # ID为空,跳出循环
            break
        name = input("请输入名字")
        if not name:   # 名字为空,跳出循环
            break
        try:
            iep = float(input("请输入智育分"))
            mep = float(input("请输入德育分"))
            sp = float(input("请输入文体分"))
        except:
            print("输入无效,请重新输入")
            continue
        # 请将输入的学生信息保存到字典
        student = {"id":id, "name":name, "iep":iep, "mep":mep, "sp":sp}
        studentList.append(student)  # 将学生字典添加到列表中
        inputMark = input("是否继续添加,(y/n):")
        if inputMark == "y":
            mark = True     # 继续添加
        else:
            mark = False    # 不继续添加

        save(studentList)   # 将学生信息保存到文件里
        print("学生信息录入完毕")


def delete():
    mark = True   # 标记是否循环
    while mark:
        studentId = input("请输入要删除的学生ID:")
        if studentId is not "":                     # 判断输入是否要删除的学生
            if os.path.exists("student.txt"):    # 判断文件是否存在
                with open("student.txt", 'r') as rfile:  # 打开文件
                    student_old = rfile.readlines() # 读取全部内容
            else:
                student_old = []
            ifdel = False
            if student_old:       #标记是否删除
                with open('student.txt', 'w') as wfile:
                    d = {}
                    for list in student_old:
                        d = dict(eval(list))   # 字符串转字典
                        if d['id'] != studentId:
                            wfile.write(str(d)+'\n')  # 将一条信息写入文件
                        else:
                            ifdel = True    # 标记已经删除
                    if ifdel:
                        print("ID为 %s 的学生信息已经被删除..." % studentId)
                    else:
                        print("没有找到ID为 %s 的学生信息..." % studentId)
            else:
                print("无学生信息...")
                break
            show()
            inputMark = input("是否继续删除?(y/n)")
            if inputMark == 'y':
                mark = True
            else:
                mark = False


def modify():
    show()
    if os.path.exists("student.txt"):   # 判断文件是否存在
        with open("student.txt", 'r') as rfile:
            student_old = rfile.readlines()   # 读取全部文件内容
    else:
        return
    studentid = input("请输入要修改的学生的ID:")
    with open("student.txt", 'w') as wfile:
        for student in student_old:
            d = dict(eval(student))
            if d['id'] == studentid:    # 是否为要修改的学生
                print("找到这名学生,可以修改他的信息!")
                while True:
                    try:
                        d['name'] = input("请输入名字")
                        d['iep'] = float(input("请输入智育分"))
                        d['mep'] = float(input("请输入德育分"))
                        d['sp'] = float(input("请输入文体分"))
                    except:
                        print("你的输入有误,请重新输入")
                    else:
                        break
                student = str(d)             # 字典转化为字符串
                wfile.write(student + "\n")  # 将修改的信息写入到文件
                print("修改成功")
            else:
                wfile.write(student)    # 将未修改的信息写入到文件
    mark = input("是否继续修改其他同学的信息?(y/n):")
    if mark == 'y':
        modify()


def search():
    mark = True
    student_query = []   # 用于保存查询结果的时间的列表
    while mark:
        id = ""
        name = ""
        if os.path.exists("student.txt"):
            mode = input("按ID查询请输入1, 按名字查询请输入2:")
            if mode == '1':
                id = input("请输入学生ID")
            elif mode == '2':
                name = input("请输入学生名字")
            else:
                print("你的输入有误,请重新输入!")
                search()                           # 重新查询
            with open("student.txt", 'r') as file:
                student = file.readlines()         # 读取文件全部信息
                for list in student:
                    d = dict(eval(list))
                    if id is not "":    # 判断是否按ID查询
                        if d['id'] == id:
                            student_query.append(d)    # 将找到的学生保存到信息列表中
                    elif name is not "":
                        if d['name'] == name:
                            student_query.append(d)    # 将找到的学生保存到信息列表中
                show_student(student_query)  # 显示查询结果
                student_query.clear()        # 清空列表
                inputMark = input("是否继续查询?(y/n)")
                if inputMark == 'y':
                    mark = True
                else:
                    mark = False
        else:
            print("暂时未保存信息。。。")
            return


def show_student(studentList):
    if not studentList:
        print("无相关数据")
        return
    # 定义标题格式
    format_title = "{:^12}{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}"
    # 按指定格式显示标题
    print(format_title.format("ID", "名字", "智育分", "德育分", "文体分", "总分"))
    # 定义具体内容格式
    format_data = "{:^12}{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}"
    for info in studentList:
        print(format_data.format(info.get("id"),
                                 info.get("name"),
                                 str(info.get("iep")),
                                 str(info.get("mep")),
                                 str(info.get("sp")),
                                 str(info.get("iep")*0.7+info.get("mep")*0.2+info.get("sp")*0.1).center(12)))



def total():
    if os.path.exists("student.txt"):
        with open("student.txt", 'r') as rfile:
            student_old = rfile.readlines()
            if student_old:
                print("一共有 %d 名学生!" % len(student_old))
            else:
                print("还没有录入学生信息!")
    else:
        print("暂未保存数据信息。。。")


def show():
    student_new = []
    if os.path.exists("student.txt"):
        with open("student.txt", 'r') as rfile:
            student_old = rfile.readlines()
        for list in student_old:
            student_new.append(eval(list))  # 将找到的学生信息保存到列表中
        if student_new:
            show_student(student_new)
    else:
        print("暂未保存数据信息")


def sort():
    show()
    if os.path.exists("student.txt"):
        with open("student.txt", 'r') as rfile:
            student_old = rfile.readlines()
            student_new = []
        for list in student_old:
            d = dict(eval(list))     # 字符串转字典
            student_new.append(d)    # 将转换后的字典添加到列表里
    else:
        return
    ascORdesc = input("请选择0(升序)/1(降序):")
    if ascORdesc == '0':
        ascORdescBool = False
    elif ascORdesc == '1':
        ascORdescBool = True
    else:
        print("你输入的有误,请重新输入!")
        sort()
    mode = input("请选择排序方式(1按智育分排序;2按德育分排序;3按文体分排序;0按总分排序):")
    if mode == '1':
        student_new.sort(key=lambda x: x["iep"], reverse=ascORdescBool)
    elif mode == '2':
        student_new.sort(key=lambda x: x["mep"], reverse=ascORdescBool)
    elif mode == '3':
        student_new.sort(key=lambda x: x["sp"], reverse=ascORdescBool)
    elif mode == '0':
        student_new.sort(key=lambda x: x["iep"]*0.7+x["mep"]*0.2+x["sp"]*0.1, reverse=ascORdescBool)
    else:
        print("你的输入有误,请重新输入!")
        sort()
    show_student(student_new)


if __name__ == "__main__":
    main()

五、说明

项目的核心是对文件、字典、列表的操作。当然还有很多不足,有想法的欢迎的评论区提出

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章