用Python实现一个基于文件存储的控制台学生管理系统
放假回家,写写Python玩,10分钟写了一个基于文件存储的控制台学生管理系统,目的是熟悉Json的使用
import json
import os
import atexit
import time
latest_file = ""
def main():
read_now_time() #程序刚启动时读取上次保存的时间戳文件
while(True):
print_menu()
choose = int(input("输入您的选项:"))
if choose==1:
add_stu()
elif choose==2:
delete_stu()
elif choose==3:
update_stu()
elif choose==4:
display_stu()
else:
exit()
def print_menu():
print ("====================================================")
print ("1.添加学生信息 2.删除学生信息 3.更新学生信息 4.显示学生信息 5.退出")
print ("====================================================")
def add_stu():
id = input("输入学生证件号:")
name = input("输入学生姓名:")
grade = input("输入学生成绩:")
student = {"id": id, "name": name, "grade": grade}
students = read_json(from_add=True)
if not students:
students = [student]
else:
students.append(student)
write_json(students)
def delete_stu():
students = read_json()
id = input("输入要删除学生的证件号:")
find_id = False
for student in students:
if id == student['id']:
find_id = True
print ("学生号:" + id + ",姓名:" + student['name'], ",成绩:" + student['grade'])
sure = input("确认要删除该学生信息吗:Y/N")
if sure=="Y":
students.remove(student)
write_json(students)
break
if not find_id:
print("未找到该学生")
def update_stu():
print("待定......")
def display_stu():
students = read_json()
for student in students:
print ("----->" + "学生证件号:" + student['id'] + ",学生姓名:" + student['name'] + ",学生成绩:" + student['grade'])
def read_json(from_add=False):
if not latest_file:
if not from_add:
print ("请先添加学生")
return None
file_dir = os.path.join(os.getcwd(), "json")
file_path = os.path.join(file_dir, latest_file)
with open(file_path, "r+", encoding="utf-8") as fp:
json_dict = json.load(fp)
return json_dict
def write_json(json_dict):
global latest_file
file_dir = os.path.join(os.getcwd(), "json")
if not os.path.exists(file_dir):
os.mkdir(file_dir)
file_name = str(int(time.time()))
latest_file = file_name
file_path = os.path.join(file_dir, file_name)
json_data = json.dumps(json_dict)
with open(file_path, "w+") as fp:
fp.write(json_data)
def read_now_time():
global latest_file
now_time_file = os.path.join(os.getcwd(), "now")
if not os.path.exists(now_time_file):
print ("时间戳文件不存在,无法定位上次保存的学生数据,重新开始保存数据")
return
with open(now_time_file, "r+") as fp:
latest_file = fp.readline().strip()
if not latest_file:
print("时间戳文件为空,无法定位上次保存的学生数据,重新开始保存数据")
else:
print("时间戳文件为:" + latest_file + ",加载上次保存的数据......")
#程序退出时,自动保存当前时间戳
@atexit.register
def write_now_time():
if not latest_file:
return
now_time_file = os.path.join(os.getcwd(), "now")
with open(now_time_file, "w+") as fp:
fp.write(latest_file)
if __name__ == '__main__':
main()