服务器之家

服务器之家 > 正文

Python实现学生管理系统的代码(JSON模块)

时间:2021-10-06 00:35     来源/作者:stan Z

构思

学生管理系统 应该包含老师注册登录 管理学生信息(增删改查)还有数据持久化

因为数据存入JSON文件 增删改查都需要读取和修改文件
所以需要一个读写文件的方法文件 file_manager
密码加密可以用到哈希模块文件 tools
老师和学生的类文件 model
程序入口(主页)文件index
核心增删改查文件 student_manager

file_manager.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""
Project: ClassStudent
Creator: 猫猫
Create time: 2021-02-25 20:23
IDE: PyCharm
Introduction:https://blog.csdn.net/Cantevenl/article/details/115439530
"""
base_dir = 'files/'  # 定义一个变量 文件路径
 
 
# 读文件的函数
def read_file(file_name):
    try:
        with open(base_dir + file_name, 'r', encoding='utf8') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        print('文件未找到')
 
 
def write_json(file_name, data):
    with open(base_dir + file_name, 'w', encoding='utf8') as file:
        import json
        json.dump(data, file)
 
 
def read_json(file_name, default_data):
    try:
        with open(base_dir + file_name, 'r', encoding='utf8') as file:
            import json
            return json.load(file)
    except FileNotFoundError:
        # print('文件未找到')
        return default_data

tools.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Project: ClassStudent
Creator: 猫猫
Create time: 2021-02-25 20:24
IDE: PyCharm
Introduction:https://blog.csdn.net/Cantevenl/article/details/115439530
"""
# 加密密码
import hashlib
 
def encrypt_password(passwd, x='zhumaogouniu'):
    h = hashlib.sha256()
    h.update(passwd.encode('utf8'))
    h.update(x.encode('utf8'))
    return h.hexdigest()

model.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
Project: ClassStudent
Creator: 猫猫
Create time: 2021-02-25 20:24
IDE: PyCharm
Introduction:https://blog.csdn.net/Cantevenl/article/details/115439530
"""
# 创建一个老师对象
class Teacher(object):
    def __init__(self, name, password):
        import tools
        self.name = name
        self.password = tools.encrypt_password(password)
 
class Student(object):
    def __init__(self, s_id, name, age, gender, tel):
        self.s_id = s_id
        self.name = name
        self.age = age
        self.gender = gender
        self.tel = tel

index.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""
Project: ClassStudent
Creator: 猫猫
Create time: 2021-02-25 20:25
IDE: PyCharm
Introduction:https://blog.csdn.net/Cantevenl/article/details/115439530
"""
import sys
import file_manager  # 导入自己写的读取文件模块
import model
import student_manager
 
def register():
    # 读取文件,查看文件里是否有数据。如果文件不存在,默认是一个字典
    data = file_manager.read_json('data.json', {})
    while True:
        teacher_name = input('请输入账号(3~6位):')
        if not 2 <= len(teacher_name) <= 6:
            print('账号不符合要求,请重新输入!')
        else:
            break
    if teacher_name in data:
        print('注册失败!该账号已经被注册!')
        return
 
    while True:
        password = input('请输入密码(6~12位):')
        if not 6 <= len(password) <= 12:
            print('密码不符合要求,请重新输入!')
        else:
            break
 
    # 用户名密码都已经输入正确以后 将用户名和密码以key:value形式储存
    # 可以创建一个teacher对象
    t = model.Teacher(teacher_name, password)
    data[t.name] = t.password
    file_manager.write_json('data.json', data)
 
def login():
    # 读取文件,查看文件里是否有数据。如果文件不存在,默认是一个字典
    data = file_manager.read_json('data.json', {})
    teacher_name = input('请输入老师账号:')
 
    if teacher_name not in data:
        print('登录失败!该账号没有注册!')
        return
    password = input('请输入密码:')
    import tools
    if data[teacher_name] == tools.encrypt_password(password):
        student_manager.name = teacher_name
        print('登录成功')
        student_manager.show_manager()
    else:
        print('密码错误,登陆失败!')
 
def start():
    content = file_manager.read_file('welcome.txt')
    while True:
        operate = input(content + '\n请选择(1-3):')
        if operate == '1':
            print('登录')
            login()
        elif operate == '2':
            print('注册')
            register()
        elif operate == '3':
            print('退出')
            # break   # 把循环退出
            # exit(0)   # 退出整个程序
            sys.exit(0# 退出程序
        else:
            print('输入有误!')
 
if __name__ == '__main__':
    start()

student_manager.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""
Project: ClassStudent
Creator: 猫猫
Create time: 2021-02-25 20:26
IDE: PyCharm
Introduction:https://blog.csdn.net/Cantevenl/article/details/115439530
"""
import file_manager
import model
 
name = ''
 
 
# 添加
def add_student():
    x = file_manager.read_json(name + '.json', {})
    if not x:
        students = []
        num = 0
    else:
        students = x['all_student']
        # s_id通过json字典里的num来生成
        num = int(x['num'])
    while True:
        s_name = input('请输入学生姓名:')
        s_age = input('请输入年龄:')
        s_gender = input('请输入性别:')
        s_tel = input('请输入电话号码:')
 
        num += 1
        # 字符串的zfill方法,在字符串的前面补0
        s_id = 'student_id_' + str(num).zfill(3)
 
        # 创建一个Student对象
        s = model.Student(s_id, s_name, s_age, s_gender, s_tel)
 
        students.append(s.__dict__)
        # 拼接字典
        data = {'all_student': students, 'num': len(students)}
        # 把数据写入到文件里 以老师名字.json 把data写进去
        file_manager.write_json(name + '.json', data)
        choice = input('添加成功!\n1.继续\n2.返回\n请选择(1-2):')
        if choice == '2':
            break
 
 
# 显示 查找
def show_student():
    choice = input('1.查看所有学生\n2.根据姓名查找\n3.根据学号查找\n其他:返回\n请选择:')
    students = file_manager.read_json(name + '.json', {})
    
    all_students = students.get('all_student', [])  # get拿列表里的数据,拿不到默认是一个空列表[]
    if not all_students:
        print('该老师没有学生,请添加学生')
        return
 
    if choice == '1'# 查看所有学生
        pass
    elif choice == '2'# 根据姓名查看
        s_name = input('请输入学生的姓名:')
        all_students = filter(lambda s: s['name'] == s_name, all_students)  # students就只保留了指定名字的学生
    elif choice == '3'# 学号查找
        s_id = input('请输入学生的学号:')
        all_students = filter(lambda s: s['s_id'] == s_id, all_students)
    else:
        return
 
    if not students:
        print('未找到学生')
        return
 
    for student in all_students:
        print('学号:{s_id},姓名:{name},性别:{gender},年龄{age},电话号码{tel}'.format(**student))
 
 
# 修改
def modify_student():
    key = value = ''
    m = file_manager.read_json(name + '.json', {})
    all_students = m.get('all_student', [])
 
    if not all_students:
        print('该老师没有学生,请添加学生')
        return
 
    modify = input('1.根据姓名修改\n2.根据学号修改\n其他:返回\n请选择:')
    if modify == '1':
        value = input('请输入要修改的学生名字:')
        key = 'name'
 
    elif modify == '2':
        value = input('请输入要修改的学生学号:')
        key = 's_id'
 
    else:
        return
 
    students = list(filter(lambda s: s[key] == value, all_students))
    if not all_students:
        print('没有找到对应的学生')
        return
 
    for i, student in enumerate(students):
        print('{xiabiao} 学号:{s_id},姓名:{name},性别:{gender},年龄{age},电话号码{tel}'.format(xiabiao=i, **student))
 
    n = int(input('请输入需要修改的学生的标号(0~{}),q-->返回:'.format(len(students) - 1)))
 
    if not 0 <= n <= len(students):
        print('输入的内容错误')
        return
 
    all_students.remove(students[n])
 
    students[n]['s_id'] = new_input((students[n]['s_id']), "请输入修改后的学生学号[回车则不修改]:")
    students[n]['name'] = new_input((students[n]['name']), "请输入修改后的学生姓名[回车则不修改]:")
    students[n]['gender'] = new_input((students[n]['gender']), "请输入修改后的学生性别[回车则不修改]:")
    students[n]['age'] = new_input((students[n]['age']), "请输入修改后的学生年龄[回车则不修改]:")
    students[n]['tel'] = new_input((students[n]['tel']), "请输入修改后的学生电话号码[回车则不修改]:")
    all_students.append(students[n])
    print(all_students)
    m['all_student'] = all_students
    file_manager.write_json(name + '.json', m)
 
 
# 删除
def delete_student():
    y = file_manager.read_json(name + '.json', {})
    all_students = y.get('all_student', [])
    key = value = ''
 
    if not all_students:
        print('该老师没有学生,请添加学生')
        return
 
    num = input('1.按照姓名删除\n2.按照学号删除\n其他:返回\n请选择:')
    if num == '1':
        key = 'name'
        value = input('请输入要删除的学生名字:')
 
    elif num == '2':
        key = 's_id'
        value = input('请输入要删除的学生学号:')
    else:
        return
 
    students = list(filter(lambda s: s.get(key, '') == value, all_students))
    if not students:
        print('没有找到对应的学生')
        return
 
    for i, student in enumerate(students):
        print('{xiabiao} 学号:{s_id},姓名:{name},性别:{gender},年龄{age},电话号码{tel}'.format(xiabiao=i, **student))
 
    n = input('请输入需要删除的学生的标号(0~{}),q-->返回:'.format(len(students) - 1))
 
    if not n.isdigit() or not 0 <= int(n) <= len(students):
        print('输入的内容错误')
        return
 
    # 将学生从all_students里删除
    # all_students.pop(n)
    all_students.remove(students[int(n)])
 
    # 更新新的名单
    y['all_student'] = all_students
    file_manager.write_json(name + '.json', y)
 
 
# 显示管理页面
def show_manager():
    content = file_manager.read_file('students_page.txt') % name
    while True:
        print(content)
        operate = input('请选择(1-5):')
        if operate == '1':
            add_student()
        elif operate == '2':
            show_student()
        elif operate == '3':
            modify_student()
        elif operate == '4':
            delete_student()
        elif operate == '5':
            break
        else:
            print('输入错误!')
 
 
# 修改时用的input方法
def new_input(old, new):
    input_str = input(new)
 
    if len(input_str) > 0:
        return input_str
    else:
        return old

美化文本

通过自己写的读取文件方法可以直接读取文本(类似界面)

welcome.txt

?
1
2
3
4
5
6
7
8
================================
    ** 欢迎来到学生管理系统**
 
           1. 登    录
           2. 注    册
           3. 退    出
    **                    **
================================

students_page.txt

?
1
2
3
4
5
6
7
8
9
10
================================
❀❀ 欢迎%s老师进入学生管理系统:
 
         1.  添加学生
         2.  查看学生
         3.  修改学生信息
         4.  删除学生
         5.  返回
❀❀                          ❀❀
================================

执行效果

Python实现学生管理系统的代码(JSON模块)
Python实现学生管理系统的代码(JSON模块)
Python实现学生管理系统的代码(JSON模块)

到此这篇关于Python实现学生管理系统的代码(JSON模块)的文章就介绍到这了,更多相关Python学生管理系统内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/Cantevenl/article/details/115439530

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部