学生管理系统
student.py
# -*- coding: utf-8 -*-
"""
@project: day12-文件操作和异常处理
@file: student.py
@author: wanglei
@time: 2019-08-06 16:41:14
"""
import datetime
class User(object):
def __init__(self, name, password):
self._name = name
self._password = password
self._file_path = ''.join(['files/', str(name), '_', datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
, '.pkl'])
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def password(self):
return self._password
@password.setter
def password(self, pwd):
self._password = pwd
@property
def file_path(self):
return self._file_path
def __repr__(self) -> str:
return 'User[user_name = ' + self.name \
+ ', password = ' + self.password + \
', files = ' + self.file_path + ']'
class Student(object):
def __init__(self, sid, name, age, phone):
self._sid = sid
self._name = name
self._age = age
self._phone = phone
@property
def sid(self):
return self._sid
@sid.setter
def sid(self, sid):
self._sid = sid
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def age(self):
return self._age
@age.setter
def age(self, age):
self._age = age
@property
def phone(self):
return self._phone
@phone.setter
def phone(self, phone):
self._phone = phone
def __repr__(self) -> str:
return self.sid + '\t' + self.name + '\t\t' + str(self.age) + '\t\t' + self.phone
studentManage.py
# -*- coding: utf-8 -*-
"""
@project: day12-文件操作和异常处理
@file: studentManage.py
@author: wanglei
@time: 2019-08-06 16:41:14
"""
from student import *
import _pickle as pickle
import os
file_path = ''
user = User(None, None)
USER_DIR_PATH = 'files/user.pkl'
def stu_is_exist(fn):
"""装饰器,判断学生文件及打印学生信息"""
def show_info():
"""打印学生信息"""
with open(file_path, 'br') as f_stu:
try:
stu_list = pickle.load(f_stu)
print('=' * 30)
print('序号\t\t学生姓名\t学生年龄\t学生电话\t')
for stu in stu_list:
print(stu)
print('=' * 30)
except EOFError:
print('学生信息不存在,请先进行添加!')
welcome()
# 判断信息文件是否存在
def exist(*args, **kwargs):
if not os.path.exists(file_path):
with open(file_path, mode='bw') as f:
f.close()
with open(file_path, mode='bw') as f_stu:
pickle.dump([], f_stu, True)
print('=' * 30)
print('学生信息文件不存在,重新创建成功!')
welcome()
else:
show_info()
fn(*args, **kwargs)
show_info()
print('1.继续\n2.返回')
choose_num = input('请选择1~2:')
while True:
if choose_num == '1':
show_info()
fn(*args, **kwargs)
show_info()
elif choose_num == '2':
welcome()
else:
print('输入错误,请重新输入!\n')
print('1.继续\n2.返回')
choose_num = input('请选择1~2:')
return exist
def login():
"""登录"""
print('=' * 30)
print('\t** 欢迎来到 xx 管理系统 **\n')
print('\t♦️\t1.\t登\t\t录\n\t♦️\t2.\t注\t\t册\n\t♦️\t3.\t退\t\t出')
print('\n', '=' * 30)
choose_num = input('请选择1~3:')
while True:
if choose_num == '1':
user_login_verify()
break
elif choose_num == '2':
user_login_register()
break
elif choose_num == '3':
print('欢迎下次使用~')
exit(0)
else:
print('输入错误,请重新输入!\n')
choose_num = input('请选择1~3:')
def user_login_verify():
"""用户登录验证"""
if os.path.exists(USER_DIR_PATH):
with open(USER_DIR_PATH, 'br') as f_user:
try:
user_list = pickle.load(f_user)
# print(user_list)
user_name, password = user_info_verify()
for u in user_list:
if u.name == user_name and u.password == password:
global user
user = u
global file_path
file_path = user.file_path
# print(file_path)
if not os.path.exists(file_path):
with open(file_path, mode='bw') as f:
f.close()
with open(file_path, mode='bw') as f_stu:
pickle.dump([], f_stu, True)
print('=' * 30)
print('学生信息文件不存在,重新创建成功!')
welcome()
return
if user_name not in [u.name for u in user_list]:
print('该用户名尚未注册,请先进行注册!')
login()
return
print("用户名或密码错误,请重试!")
login()
except EOFError:
print("用户信息不存在...")
print('=' * 30)
print('跳转注册...')
user_login_register()
else:
with open(USER_DIR_PATH, mode='w'):
print('=' * 30)
print("用户文件不存在,重新用户文件成功!")
print('=' * 30)
print('跳转注册...')
user_login_register()
def user_login_register():
"""用户注册"""
user_name, password = user_info_verify()
if not os.path.exists(USER_DIR_PATH):
with open(USER_DIR_PATH, mode='bw'):
print('=' * 30)
print('用户信息文件不存在,重新创建成功!')
with open(USER_DIR_PATH, 'br') as f_user:
try:
user_list = pickle.load(f_user)
except EOFError:
user_list = []
for u in user_list:
if u.name == user_name:
print('用户名已存在, 请进行登录!')
login()
new_user = User(user_name, password)
user_list.append(new_user)
with open(USER_DIR_PATH, 'wb') as f_user:
pickle.dump(user_list, f_user, True)
print("用户注册成功!")
login()
def user_info_verify():
while True:
user_name = input('请输入用户名(3-6位):')
if 3 <= len(user_name) <= 6:
break
else:
print('输入有误,用户名长度必须为3-6位!')
while True:
password = input('请输入密码(6-12位):')
if 6 <= len(password) <= 12:
break
else:
print('输入有误,密码长度必须为6-12位!')
return user_name, password
def welcome():
"""欢迎页面"""
print('=' * 30)
print('欢迎%s:' % user.name)
func_list = ['添加学生', '查看学生', '修改学生信息', '删除学生', '返回']
for i in range(len(func_list)):
print('❤ %d.\t %s' % (i + 1, func_list[i]))
print('=' * 30)
choose_func()
def choose_func():
"""选择功能"""
choose_num = input('请选择1-5:')
if choose_num == '1':
add_stu()
elif choose_num == '2':
get_stu()
elif choose_num == '3':
set_stu()
elif choose_num == '4':
del_stu()
elif choose_num == '5':
print('亲爱的%s,欢迎下次使用,bye~' % user.name)
login()
else:
print('输入错误,请重新输入!\n')
choose_func()
def stu_info_verify():
while True:
stu_name = input('请输入学生姓名:')
if stu_name.isdigit():
print('输入有误,学生姓名不能为数字!')
else:
break
while True:
stu_age = input('请输入学生年龄:')
if stu_age.isdigit():
stu_age = int(stu_age)
break
else:
print('输入有误,学生年龄请输入数字!')
while True:
stu_phone = input('请输入学生电话:')
if stu_phone.isdigit():
break
else:
print('输入有误,学生电话信息请输入数字!')
return stu_name, stu_age, stu_phone
@stu_is_exist
def add_stu():
"""增加学生信息"""
with open(user.file_path, 'br') as f_stu:
try:
stu_list = pickle.load(f_stu)
f_stu.close()
except EOFError:
stu_list = []
if not stu_list:
stu_sid = '1'.zfill(5)
else:
stu_sid = str(int(stu_list[-1].sid) + 1).zfill(5)
stu_name, stu_age, stu_phone = stu_info_verify()
new_student = Student(stu_sid.zfill(5), stu_name, stu_age, stu_phone)
stu_list.append(new_student)
with open(user.file_path, 'wb') as f_stu:
pickle.dump(stu_list, f_stu, True)
f_stu.close()
print("学生信息添加成功!")
@stu_is_exist
def get_stu():
"""查看学生信息"""
input('请按任意键返回:')
welcome()
@stu_is_exist
def set_stu():
"""修改学生信息"""
with open(user.file_path, 'br') as f_stu:
try:
stu_list = pickle.load(f_stu)
is_find = False
stu_sid = int(input('请输入想要修改的序号:'))
for index in range(len(stu_list)):
if int(stu_list[index].sid) == stu_sid:
stu_list[index].name, stu_list[index].age, stu_list[index].phone = stu_info_verify()
is_find = True
break
f_stu.close()
except EOFError:
print('学生信息不存在,请先进行添加!')
welcome()
if not is_find:
print('序号不存在,请重试!')
welcome()
with open(user.file_path, 'wb') as f_stu:
pickle.dump(stu_list, f_stu, True)
f_stu.close()
print("学生信息修改成功!")
@stu_is_exist
def del_stu():
"""删除学生信息"""
with open(user.file_path, 'br') as f_stu:
try:
stu_list = pickle.load(f_stu)
is_find = False
stu_sid = int(input('请输入想要删除的序号:'))
for index in range(len(stu_list)):
if int(stu_list[index].sid) == stu_sid:
del stu_list[index]
is_find = True
break
f_stu.close()
except EOFError:
print('学生信息不存在,请先进行添加!')
welcome()
if not is_find:
print('序号不存在,请重试!')
del_stu()
with open(user.file_path, 'wb') as f_stu:
pickle.dump(stu_list, f_stu, True)
f_stu.close()
print("学生信息删除成功!")
if __name__ == '__main__':
login()