學生資訊系統(json模組解決數據持久化
將學生管理的案例,學生資訊由原來的只有姓名,拓展為包含,姓名,年齡,兩個屬性;完成對應的增、刪、查、改,操作
import json,os,time,sys student_list = [] File_path = 'name.txt' #從文件中讀取之前存儲的數據(考慮是否有對應文件的問題,要做文件是否存在的判斷),然後將讀取到的數據存儲到列表 def dataRead(filepath): # 判斷filepath這個路徑對應的文件是否存在: if os.path.exists(filepath): print('找到提取文件') f1 = open(filepath,'r',encoding='utf-8') global student_list student_list = json.load(f1) print('學生資訊',student_list) f1.close() print('讀取數據成功') else: print('文件不存在') def addStudent(): name = input('請輸入學生姓名:') age = int(input('請輸入學生年齡:')) stu_dict = { 'name':name, 'age':age } student_list.append(stu_dict) print('學生資訊添加成功,1秒後自動返回主菜單nnn') time.sleep(1) def delStudent(): name = input('請輸入要刪除的學生姓名:') for stu in student_list: if name == stu['name']: student_list.remove(stu) print('刪除成功') else: print('該學生資訊不存在') def updateStudent(): name = input("請輸入要修改的學生姓名:") for stu in student_list: if name == stu['name']: new_name = input("請輸入修改後的姓名:") new_age = eval(input("請輸入修改後的年齡:")) stu['name'] = new_name stu['age'] = new_age print('修改成功') break else: print('該學生資訊不存在') # name = input('請輸入要修改的學生姓名:') # age = int(input('請輸入修改學生的年齡:')) # new_dict = {'name':name,'age':age} # if new_dict in student_list : # index = student_list.index(new_dict) # # new_name = input('請輸入修改後的學生姓名:') # new_age = int(input('請輸入修改後的學生年齡:')) # # # student_list[index]['name'] = new_name # student_list[index]['age'] = new_age # print('修改成功') # else: # # print('該學生資訊不存在') def queryStudent(): name = input('請輸入要查詢的學生姓名:') for stu in student_list: if name == stu['name']: print('學生資訊:',stu) break else: print('該學生資訊不存在') def showAll(): print('所有學生資訊如下:') for stu in student_list: print('姓名:{},年齡:{}'.format(stu.get('name'),stu.get('age'))) def systemExit(): dataWrite(File_path) print('謝謝使用') sys.exit() #將列表中的數據寫入文件 def dataWrite(filepath): f = open(filepath,'w',encoding='utf-8') json.dump(student_list,f) f.close() print('數據寫入成功') #從文件中載入數據 dataRead(File_path) while True: print('1.添加學生') print('2.刪除學生') print('3.修改學生') print('4.查詢學生') print('5.展示所有') print('6.退出系統') num = input('請輸入1-6的數字進入相應功能:') print('------'*6) if num == '1': addStudent() elif num == '2': delStudent() elif num == '3': updateStudent() elif num == '4': queryStudent() elif num == '5': showAll() elif num == '6': systemExit() else: print('輸入有誤')