Python学生信息管理系统(excel存储)

 删除和修改操作未完成

import row
import xlwt
import os
from openpyxl import *
# 构建workbook对象
workbook = load_workbook('stuinfo.xlsx')
def main():
    while True:
        menu()
        choice = int(input('请选择'))
        if choice in [0, 1, 2, 3, 5, 6, 7, 8, 9, 10]:
            if choice == 0:
                answer = input('您确定要退出系统吗?y/n')
                if answer == 'y' or answer == 'Y':
                    print('感谢您的使用')
                    break
                else:
                    continue
            elif choice == 1:
                insert()
            elif choice == 2:
                total()
            elif choice == 3:
                serch(read_excel_data())
            # elif choice == 4:
            #     delete()
            elif choice == 5:
                modify()
            elif choice == 6:
                sort(read_excel_data())
            elif choice == 7:
                show()
            elif choice == 8:
                all_avg(read_excel_data())
            elif choice == 9:
                subject_avg(read_excel_data())
            elif choice == 10:
                highest(read_excel_data())


def menu():
    print('功能菜单')
    print('0.退出')
    print('1.录入学生信息')
    print('2.查询学生总数')
    print('3.按姓名查找')
    print('4.删除学生信息')
    print('5.修改学生信息')
    print('6.按平均分排序')
    print('7.显示所有学生成绩')
    print('8.查所有学生平均分')
    print('9.每科平均分')
    print('10.查询每科最高分')


def insert():
    student_list = []
    while True:

        name = input('请输入姓名:')
        if not name:
            break

        try:
            english = int(input('请输入英语成绩'))
            python = int(input('请输入Python成绩'))
            java = int(input('请输入java成绩'))
        except:
            print('输入无效,请重新输入')
            continue
        # 将学生信息保存到列表
        stu_info = [name, english, python, java]
        print(stu_info)
        #将学生信息保存到字典中
        # student = {'name': name, 'english': english, 'python': python, 'java': java}
        # print(student)
        #将学生信息添加到列表中
        student_list.append(stu_info)
        # print(student_list)
        # 将从界面输入的数据封装成列表
        stu_info = [name, english, python, java]
        sheet = workbook.active
        row = sheet.max_row + 1
        column = sheet.max_column + 1
        for data_cell in range(1, column):
            sheet.cell(row=row, column=data_cell, value=stu_info[data_cell-1])
        workbook.save(filename='stuinfo.xlsx')
        answer = input('是否继续添加? y/n \n')
        if answer == 'y':
            continue
        else:
            break

    #调用save()函数
    # save(student_list)
    print('学生信息录入完毕')
    # print(student_list)

def save(lst):
    pass
    # try:
    #     stu_txt = open(filename, 'a', encoding='utf-8')
    # except:
    #     stu_txt = open(filename, 'w', encoding='utf-8')
    # for item in lst:
    #     stu_txt.write(str(item)+'\n')
    # stu_txt.close()

def total():

    read_excel_data()
    work_book = load_workbook('stuinfo.xlsx')
    sheet = work_book.active
    stuinfo_list = []
    # print(sheet.max_row)
    print('一共有' + str(sheet.max_row) + '名学生')


def serch(score):
    a = input("请输入学生姓名:")
    flag = False
    for s in score:
        if a == s[0]:
            flag = True
            print('姓名:%s 英语成绩:%.1f  Python成绩:%.1f  Java成绩:%.1f '
                  % (s[0], s[1], s[2], s[3]))
            break
    if flag == False:
        print("未查询到该学生信息")

    # student_query = []
    # while True:
    #     id = ''
    #     name = ''
    #     if os.path.exists('stuinfo.xlsx'):
    #         mode = input('按id查找请输入1,按姓名查找请输入2:')
    #         if mode == '1':
    #             id = input('请输入学生id')
    #         elif mode == '2':
    #             name = input('请输入学生姓名:')
    #         else:
    #             print('您的输入有误,请重新输入')
    #             serch()
    #             rfile = read_excel_data()
    #             print(rfile)
    #             # for item in student:
    #             #     d = dict(eval(item))
    #             #     if id != '':
    #             #         if d['id'] == id:
    #             #             student_query.append(d)  # 查到的学生添加到列表里
    #             #     elif name != '':
    #             #         if d['name'] == name:
    #             #             student_query.append(d)
    #         #显示查询结果
    #         show_student(student_query)
    #         #清空列表
    #         student_query.clear()
    #         answer = input('是否要继续查询?y / n\n')
    #         if answer == 'y':
    #             continue
    #         else:
    #             break
    #     else:
    #         print('暂未保存学生信息')
    #         return




# def delete():
#     while True:
#         student_id = input('请输入要删除的学生的id:')
#         if student_id != '':
#             if os.path.exists('stuinfo.xlsx'):
#
#             else:
#
#             flag = False  # 标记是否删除
#             if student_old:
#                 with open('stuinfo.xlsx', 'w', encoding='utf-8') as wfile:
#                     d = {}
#                     for item in student_old:
#                         d = dict(eval(item)) # 将字符串转成字典
#                         if d['id'] != student_id:
#                             wfile.write(str(d) + '\n')
#                         else:
#                             flag = True
#                     if flag:
#                         print(f'id为[student_id]的学生信息已被删除')
#                     else:
#                         print(f'没有找打ID为[student_id]的学生信息')
#             else:
#                 print('无学生信息')
#                 break
#             show()
#             answer = input('是否继续删除?y / n')
#             if answer == 'y':
#                 continue
#             else:
#                 break


def se_stu(score):
    a=input("请输入学生姓名:")
    flag=False
    for s in score:
        if a==s[0]:
            flag=True
            print('姓名:%s 英语成绩:%.1f  Python成绩:%.1f  Java:%.1f '
                  % (s[0], s[1], s[2], s[3]))
            break
    if flag==False:
        print("未查询到该学生信息")

def modify():
    pass
    # show()
    # if os.path.exists(filename):
    #     with open(filename, 'r', encoding='utf-8') as rfile:
    #         student_old = rfile.readlines()
    # else:
    #     return
    # student_id = input('请输入要修改的学生的ID:')
    # with open(filename, 'w', encoding='utf-8') as wfile:
    #     for item in student_old:
    #         d = dict(eval(item))
    #         if d['id'] == student_id:
    #             print('找到学生信息,可以修改其他的相关信息了!')
    #             while True:
    #                 try:
    #                     d['name'] = input('请输入姓名:')
    #                     d['english'] = input('请输入英语成绩:')
    #                     d['python'] = input('请输入Python成绩:')
    #                     d['java'] = input('请输入java成绩:')
    #                 except:
    #                     print('您的输入有误,请重新输入')
    #                 else:
    #                     break
    #             wfile.write(str(d) + '\n')
    #             print('修改成功')
    #         else:
    #             wfile.write(str(d) + '\n')
    #         answer = input('是否继续修改其他学生信息?y / n')
    #         if answer == 'y':
    #             modify()



def all_avg(scores):
    print('---------全部学生平均分-----------')
    print('\t\t\t平均分')
    sum1 = 0
    sum2 = 0
    for i in scores:
        sum1 = i[1] + i[2] + i[3]
        sum2 += sum1
    print('\t\t\t%d' % (sum2 / (len(scores) * 3)))




def subject_avg(scores):
    print('---------每一科平均分-----------')
    print('\t英语\t\tPython\tJava')
    sum_chinese = 0
    sum_math = 0
    sum_english = 0
    for i in scores:
        sum_chinese += i[1]
        sum_math += i[2]
        sum_english += i[3]
    print('\t%.2f\t%.2f\t%.2f' % (sum_chinese / len(scores), sum_math / len(scores), sum_english / len(scores)))


def highest(scores):
    print('---------每科最高分的同学-----------')
    print('\t英语\tPython\tJava')
    max_score_c = 0
    max_score_m = 0
    max_score_e = 0
    max_name_c = ''
    max_name_m = ''
    max_name_e = ''
    list1 = []
    list2 = []
    for i in scores:
        list1.append(i[0])
        list2.append(i[1:4])
    scores = dict(zip(list1, list2))
    for key, value in scores.items():
        if value[0] > max_score_c:
            max_score_c = value[0]
            max_name_c = key
        if value[1] > max_score_m:
            max_score_m = value[1]
            max_name_m = key
        if value[2] > max_score_e:
            max_score_e = value[2]
            max_name_e = key
    print('\t%s\t%s\t%s' % (max_name_c, max_name_m, max_name_e))


def sort(scores):
    print('---------学生平均分-----------')
    print('\t姓名\t\t平均分')
    list1 = []
    list2 = []
    for i in scores:
        list1.append(i[0])
        list2.append(i[1:4])
    scores = dict(zip(list1, list2))
    new = {}
    for key, value in scores.items():
        average = (list(value)[0] + list(value)[1] + list(value)[2]) / len(scores)
        new[key] = average
        print('\t%s\t\t%d' % (key, average))
    print('---------学生平均分排序-----------')
    print('\t姓名\t\t平均分')
    new = list(new.items())
    new.sort(key=lambda x: x[1], reverse=True)
    for k, v in new:
        print('\t%s\t\t%d' % (k, v))


# def show_student(lst):
    # if len(lst) == 0:
    #     print('没有查询到学生信息,无数据显示!!')
    #     return
    # #定义标题显示格式
    # format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t{:^8}'
    # print(format_title.format('ID', '姓名', '英语成绩', 'Python成绩', 'Java成绩', '总成绩', '平均分'))
    # #定义显示内容格式
    # format_data = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t{:^8}'
    # for item in lst:
    #     print(format_data.format(item.get('id'),
    #                              item.get('name'),
    #                              item.get('english'),
    #                              item.get('python'),
    #                              item.get('java'),
    #                              int(item.get('english')) + int(item.get('python')) + int(item.get('java')),
    #                              int((int(item.get('english')) + int(item.get('python')) + int(item.get('java'))) / 3)
    #                              ))


def show():
    print('-----------------所有学生成绩---------------------')
    print('\t姓名\t\t\t英语\t\t\tPython\t\tJava')
    workbook = load_workbook('stuinfo.xlsx')
    sheet = workbook.active
    stuinfo_list = []
    # 读取excel表格内容
    for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row, min_col=1,
                               max_col=sheet.max_column):
        stu_temp = []
        for c in row:
            # print(c.value)
            # 将每个单元格的数据添加到列表中
            stu_temp.append(c.value)
        print('\t%s\t\t\t%d\t\t\t%d\t\t\t%d' % (stu_temp[0], stu_temp[1], stu_temp[2], stu_temp[3]))




    # else:
    #     print('暂未保存过数据')
    # print(read_excel_data())


# 解析文件的时候,先拆解文件内容再封装需要的数据格式
# 读取excel文件数据 在函数定义中, ->表示函数返回类型
def read_excel_data() -> list:
    work_book = load_workbook('stuinfo.xlsx')
    sheet = work_book.active
    stuinfo_list = []
    # 读取excel表格内容 sheet.iter_rows()方法
    for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row,
                               min_col=1, max_col=sheet.max_column):
        stu_temp = []
        # 获取每行每个单元格的数据
        for c in row:
            # 将每个单元格的数据添加到列表中
            stu_temp.append(c.value)
        # print(stu_temp)
        # 再将每个单元格的数据添加到stuinfo_list中
        stuinfo_list.append(stu_temp)
    return stuinfo_list

# print(read_excel_data())


def write_new_excel():
    #1、 构建workbook --excel文件.xlsx
    work_book = Workbook()
    # 2、构建sheet
    sheet = work_book.active
    # 3、设置sheet的title
    sheet.title = '学生信息'
    # 4、表格head

    sheet['A1'] = '姓名'
    sheet['B1'] = 'English'
    sheet['C1'] = 'Python'
    sheet['D1'] = 'Java'
    # 5、写入到excel
    work_book.save(filename='stuinfo.xlsx')
write_new_excel()


if __name__ == '__main__':
    main()


txt存储

import os
filename = 'student.txt'
def main():
    while True:
        menu()
        choice = int(input('请选择'))
        if choice in [0, 1, 2, 3, 4, 5, 6, 7]:
            if choice == 0:
                answer = input('您确定要退出系统吗?y/n')
                if answer == 'y' or answer == 'Y':
                    print('感谢您的使用')
                    break
                else:
                    continue
            elif choice == 1:
                insert()
            elif choice == 2:
                total()
            elif choice == 3:
                serch()
            elif choice == 4:
                delete()
            elif choice == 5:
                modify()

            elif choice == 6:
                sort()
            elif choice == 7:
                show()

def menu():
    print('功能菜单')
    print('0.退出')
    print('1,录入学生信息')
    print('2.查找学生总数')
    print('3.查询')
    print('4.删除学生信息')
    print('5.修改学生信息')
    print('6.排序')
    print('7.显示所有学生成绩')


def insert():
    student_list = []
    while True:
        id = input('请输入ID(如1001)')
        if not id:
            break
        name = input('请输入姓名:')
        if not name:
            break

        try:
            english = int(input('请输入英语成绩'))
            python = int(input('请输入Python成绩'))
            java = int(input('请输入java成绩'))
        except:
            print('输入无效,请重新输入')
            continue
        #将学生信息保存到字典中
        student = {'id': id, 'name': name, 'english': english, 'python': python, 'java': java}
        #将学生信息添加到列表中
        student_list.append(student)

        answer = input('是否继续添加? y/n \n')
        if answer =='y':
            continue
        else:
            break

    #调用save()函数
    save(student_list)
    print('学生信息录入完毕')
    print(student_list)

def save(lst):
    try:
        stu_txt = open(filename, 'a', encoding='utf-8')
    except:
        stu_txt = open(filename, 'w', encoding='utf-8')
    for item in lst:
        stu_txt.write(str(item)+'\n')
    stu_txt.close()

def total():
    if os.path.exists(filename):                              # 判断文件是否存在
        with open(filename, 'r', encoding='utf-8') as rfile:  # 打开文件
            students = rfile.readlines()                      # 读取全部内容
            if students:
                print(f'一共有{len(students)}名学生')
            else:
                print('还没有录入学生信息')
    else:
        print('暂未保存信息')

def serch():
    student_query = []
    while True:
        id = ''
        name = ''
        if os.path.exists(filename):
            mode = input('按id查找请输入1,按姓名查找请输入2:')
            if mode == '1':
                id = input('请输入学生id')
            elif mode == '2':
                name = input('请输入学生姓名:')
            else:
                print('您的输入有误,请重新输入')
                serch()
            with open(filename, 'r', encoding='utf-8') as rfile:
                student = rfile.readlines()
                for item in student:
                    d = dict(eval(item))
                    if id != '':
                        if d['id'] == id:
                            student_query.append(d)  # 查到的学生添加到列表里
                    elif name != '':
                        if d['name'] == name:
                            student_query.append(d)
            #显示查询结果
            show_student(student_query)
            #清空列表
            student_query.clear()
            answer = input('是否要继续查询?y / n\n')
            if answer == 'y':
                continue
            else:
                break
        else:
            print('暂未保存学生信息')
            return


def show_student(lst):
    if len(lst) == 0:
        print('没有查询到学生信息,无数据显示!!')
        return
    #定义标题显示格式
    format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t{:^8}'
    print(format_title.format('ID', '姓名', '英语成绩', 'Python成绩', 'Java成绩', '总成绩', '平均分'))
    #定义显示内容格式
    format_data = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t{:^8}'
    for item in lst:
        print(format_data.format(item.get('id'),
                                 item.get('name'),
                                 item.get('english'),
                                 item.get('python'),
                                 item.get('java'),
                                 int(item.get('english')) + int(item.get('python')) + int(item.get('java')),
                                 int((int(item.get('english')) + int(item.get('python')) + int(item.get('java'))) / 3)
                                 ))

def delete():
    while True:
        student_id = input('请输入要删除的学生的id:')
        if student_id != '':
            if os.path.exists(filename):
                with open(filename, 'r', encoding='utf-8')as file:
                    student_old = file.readlines()
            else:
                student_old = []
            flag = False  # 标记是否删除
            if student_old:
                with open(filename, 'w', encoding='utf-8') as wfile:
                    d = {}
                    for item in student_old:
                        d = dict(eval(item)) # 将字符串转成字典
                        if d['id'] != student_id:
                            wfile.write(str(d) + '\n')
                        else:
                            flag = True
                    if flag:
                        print(f'id为{student_id}的学生信息已被删除')
                    else:
                        print(f'没有找打ID为{student_id}的学生信息')
            else:
                print('无学生信息')
                break
            show()
            answer = input('是否继续删除?y / n')
            if answer == 'y':
                continue
            else:
                break


def modify():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_old = rfile.readlines()
    else:
        return
    student_id = input('请输入要修改的学生的ID:')
    with open(filename, 'w', encoding='utf-8') as wfile:
        for item in student_old:
            d = dict(eval(item))
            if d['id'] == student_id:
                print('找到学生信息,可以修改其他的相关信息了!')
                while True:
                    try:
                        d['name'] = input('请输入姓名:')
                        d['english'] = input('请输入英语成绩:')
                        d['python'] = input('请输入Python成绩:')
                        d['java'] = input('请输入java成绩:')
                    except:
                        print('您的输入有误,请重新输入')
                    else:
                        break
                wfile.write(str(d) + '\n')
                print('修改成功')
            else:
                wfile.write(str(d) + '\n')
            answer = input('是否继续修改其他学生信息?y / n')
            if answer == 'y':
                modify()



def all_avg():
    # show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()
            print(student_list[1])

        student_new = []
        for item in student_list:
            d = dict(eval(item))
            student_new.append(d)
            print(d)
    else:
        return


def subject_avg():
    pass


def highest():
    pass


def sort():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()
        student_new = []
        for item in student_list:
            d = dict(eval(item))
            # print(d)
            student_new.append(d)
    else:
        return
    asc_or_desc = input('请选择(0.升序 1. 降序):')
    if asc_or_desc == '0':
        asc_or_desc_bool = False
    elif asc_or_desc == '1':
        asc_or_desc_bool = True
    else:
        print('您的输入有误,请重新输入')
        sort()
    mode = input('请选择排序方式(1.按英语成绩排序 2. 按Python成绩排序 3.按Java成绩排序 4. 按平均成绩排序 0.按总成绩排序:')
    if mode == '1':
        student_new.sort(key=lambda x: int(x['english']), reverse=asc_or_desc_bool)
    elif mode == '2':
        student_new.sort(key=lambda x: int(x['python']), reverse=asc_or_desc_bool)
    elif mode == '3':
        student_new.sort(key=lambda x: int(x['java']), reverse=asc_or_desc_bool)
    elif mode == '4':
        student_new.sort(key=lambda x: (int(x['english']) + int(x['python']) + int(x['java'])) / 3, reverse=asc_or_desc_bool)
    elif mode == '0':
        student_new.sort(key=lambda x: int(x['english']) + int(x['python']) + int(x['java']), reverse=asc_or_desc_bool)
    else:
        print('您的输入有误,请重新输入!!!')
        sort()
    show_student(student_new)


def show():
    student_lst = []
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            students = rfile.readlines()
            for item in students:
                student_lst.append(eval(item))
            if student_lst:
                show_student(student_lst)
    else:
        print('暂未保存过数据')


if __name__ == '__main__':
    main()

你可能感兴趣的:(python,python)