1. 程式人生 > >學員管理系統-面向物件

學員管理系統-面向物件

 1 import json
 2 import os
 3 
 4 
 5 class DataToDB():
 6 
 7     def readData(self):
 8         if os.path.exists('data.txt'):
 9             with open('data.txt', 'r+', encoding='utf-8') as fp:
10                 content = fp.read()
11         else:
12             content = False
13 
14         if
content: 15 return json.loads(content) 16 else: 17 return [] 18 19 def writeData(self, data): 20 content = json.dumps(data) 21 with open('data.txt', 'w+', encoding='utf-8') as fq: 22 fq.write(content) 23 24 25 class StudentInfo(): 26
27 def __init__(self): 28 self.db = DataToDB() 29 self.stuList = self.db.readData() 30 31 # 32 def add(self, code, name, age): 33 stuinfo = {} 34 stuinfo['code'] = code 35 stuinfo['name'] = name 36 stuinfo['age'] = age 37 self.stuList.append(stuinfo)
38 39 self.db.writeData(self.stuList) 40 41 # 42 def delete(self, code): 43 for item in self.stuList: 44 if code == item['code']: 45 self.stuList.remove(item) 46 47 self.db.writeData(self.stuList) 48 49 # 50 def edit(self, code, name, age): 51 for item in self.stuList: 52 if code == item['code']: 53 item['name'] = name 54 item['age'] = age 55 56 self.db.writeData(self.stuList) 57 58 # 59 def select(self): 60 for item in self.stuList: 61 print(item) 62 63 64 stu = StudentInfo() 65 while True: 66 print("請選擇您要進行的操作") 67 checked = input("新增(A),修改(E),刪除(D),查詢(C),退出(Q)") 68 if checked == 'a': 69 code = input('請輸入學號') 70 name = input('請輸入姓名') 71 age = input('請輸入年齡') 72 stu.add(code, name, age) 73 elif checked == 'e': 74 code = input('請輸入需要修改的學號') 75 print('-----------------請輸入新的學員資訊------------------') 76 name = input('請輸入姓名') 77 age = input('請輸入年齡') 78 stu.edit(code, name, age) 79 elif checked == 'd': 80 code = input('請輸入需要刪除的學號') 81 stu.delete(code) 82 elif checked == 'c': 83 stu.select() 84 elif checked == 'q': 85 exit('拜拜了,您嘞~')