#!/usr/bin/env python#-*- coding:utf-8 -*-
defFind(class_name):
class_list=[]
tag=False
with open(‘data‘, ‘r‘, encoding=‘utf8‘) as f:for line inf:if line.strip() == ‘班级:{0}班‘.format(class_name.strip()):
class_list.append(line)
tag=Truecontinue
if tag and line.find(‘班级:‘) !=0:
class_list.append(line)if line.find(‘班级:‘) ==0:
tag=Falsereturnclass_list;defAdd(dic):#{ ‘班级‘:‘191‘,‘学生‘:[{‘姓名‘:‘张三‘,‘学号‘:‘2018001‘,‘年龄‘:18,‘性别‘:‘男‘},{‘姓名‘:‘李四‘,‘学号‘:‘2018002‘,‘年龄‘:21,‘性别‘:‘男‘},{‘姓名‘:‘小花‘,‘学号‘:‘2018003‘,‘年龄‘:18,‘性别‘:‘女‘},{‘姓名‘:‘小红‘,‘学号‘:‘2018004‘,‘年龄‘:33,‘性别‘:‘女‘}]}
class_obj =eval(dic)
class_name= class_obj[‘班级‘]
class_list=Find(class_name)if len(class_list) >0:print(‘系统中已经存在班级[%s]。‘ %(class_name))returnwith open(‘data‘, ‘a+‘, encoding=‘utf8‘) as f:
f.write(‘\n班级:%s班‘ %(class_name))for student in class_obj[‘学生‘]:
f.write(‘\n 姓名:{0} 学号:{1} 年龄:{2} 性别:{3}‘.format(student[‘姓名‘], student[‘学号‘], student[‘年龄‘],
student[‘性别‘]))print(‘添加成功!‘)defUpdate(dic):
class_obj=eval(dic)
class_name= class_obj[‘班级‘]
class_list=Find(class_name)if len(class_list) ==0:print(‘没有查询到该班级信息。‘)returnDelete(class_name)
Add(dic)print(‘更新成功!‘)defDelete(class_name):
class_list=Find(class_name)if len(class_list) ==0:print(‘没有查询到该班级信息。‘)returnclass_list=[]
tag=False
with open(‘data‘, ‘r‘, encoding=‘utf8‘) as old_file:for line inold_file:if line.strip() == ‘班级:{0}班‘.format(class_name.strip()):
tag=Truecontinue
else:if tag and line.find(‘班级:‘) !=0:continue
if line.find(‘班级:‘) ==0:
tag=False
class_list.append(line)
with open(‘data‘, ‘w‘, encoding=‘utf8‘) as new_file:for line inclass_list:
new_file.write(line)print(‘删除成功!‘)if __name__ == ‘__main__‘:whileTrue:print(‘\n1、查询 2、修改 3、添加 4、删除‘)
operation= input(‘请输入操作:‘)if (operation == ‘1‘):
class_name= input(‘请输入查询的班级名称:‘)
class_list=Find(class_name)if len(class_list) ==0:print(‘没有查询到该班级信息。‘)else:for line inclass_list:print(line, end=‘‘)elif (operation == ‘2‘):
dic= input(‘请输入修改的字典数据:‘)
Update(dic)elif (operation == ‘3‘):
dic= input(‘请输入添加的字典数据:‘)
Add(dic)elif (operation == ‘4‘):
class_name= input(‘请输入删除的班级名称:‘)
Delete(class_name)else:print("输入不正确")