Python修煉1.學生信息管理系統(文件保存,修改后有備份恢復)


#功能主要包括對學生信息的增刪改查,以及備份恢復
#編寫一個學生類,可對其進行“增,刪,改,查”,學生類屬性包括stuID,name,sex, classID
# student.py
class Stu:
stuID = ""
name = ''
sex = 'M'
classID = 'NULL'
#屬性設置get,set方法
def get_stuID(self):
return self.stuID
def set_stuID(self,stuID):
self.stuID = stuID
def get_name(self):
return self.name
def set_name(self,name):
self.name = name
def get_sex(self):
return self.sex
def set_sex(self,sex):
self.sex = sex
def get_classID(self):
return self.classID
def set_classID(self,classID):
self.classID = classID
#學生信息.py
import os
import re
import sys
import shutil
import time
import Student
global FILEPATH # 學生信息文件
global TEMPFILE # 備份文件
FILEPATH = 'student.db'
TEMPFILE = 'backup.db'
# 視圖界面
def menuView():
print("--------------------------")
print("--------------------------")
print("---------歡迎使用---------")
print("-----學生信息管理系統-----")
print("--------------------------")
print("--------------------------")
print("請稍后,系統載入中....")
time.sleep(2)
main()

def main():
while True:
os.system('cls') #清屏命令
print("---------------------")
print("1.查詢學生信息")
print("2.增加學生信息")
print("3.刪除學生信息")
print("4.修改學生信息")
print("5.恢復學生信息")
print("0.退出")
print("---------------------")
opt = input("請選擇:")
if opt == '1':
while True:
query()
opt1 = input("繼續查詢么(Y/N)?:")
if opt1 == 'Y' or opt1 == 'y' or opt1 == '':
continue
else:
break
elif opt == '2':
while True:
addMenu()
opt2 = input("繼續增加學生么(Y/N)?:")
if opt2 == 'Y' or opt2 == 'y' or opt2 == '':
continue
else:
break
elif opt == '4':
while True:
updateMenu()
opt4 = input("繼續修改么(Y/N)?:")
if opt4 == 'Y' or opt4 == 'y' or opt4 == '':
continue
else:
break
elif opt == '3':
while True:
delMenu()
opt3 = input("繼續刪除么(Y/N)?:")
if opt3 == 'Y' or opt3 == 'y' or opt3 == '':
continue
else:
break
elif opt == '5':
backup()
elif opt == '0':
exitProgram()
break
else:
print("Erro input!")
# 0.退出
def exitProgram():
print("謝謝使用,再見!")
# 1.查詢學生信息
def query():
print("1.按學號查詢\n2.按姓名查找\n3.按班級查找\n4.查詢全部學生")
opt = input('請輸入:')
# getInfo(int(opt))
if opt == '1':
getInfo(int(opt))
elif opt == '2':
getInfo(int(opt))
elif opt == '3':
getInfo(int(opt))
elif opt == '4':
getInfo(int(opt))
else:
print("輸入錯誤")
return
# 獲取學生信息
def getInfo(IDnum):
# 用戶輸入的信息
stu = ''
if IDnum == 1:
s = '學號'
IDnum -= 1
stu = input("請輸入%s:" % s)
# 正則表達式對學號,班級號進行檢查匹配(長度)
while True:
if re.match('^[0-9]{3}$', stu):
break
else:
print("學號為001-999")
stu = input("請輸入%s:" % s)
if IDnum == 2:
s = '姓名'
IDnum -= 1
stu = input("請輸入%s:" % s)
# 判斷姓名輸入是否為中文
while True:
if not is_Chinese(stu):
print('姓名請輸入中文')
else:
break
stu = input("請輸入%s:" % s)
if IDnum == 3:
s = '班級'
stu = input("請輸入%s:" % s)
# 正則表達式對學號,班級號進行檢查匹配(長度)
while True:
if re.match('^[0-9]{2}$', stu):
break
else:
print("班級號01-99")
stu = input("請輸入%s:" % s)
# 顯示所有學生信息
if IDnum == 4:
f = open(FILEPATH, 'r')
print(''.join(f.readlines()))
return
# 判斷是否找到
flag = False
# 讀取文件內容 找到打印出來,未找到給出提示
with open(FILEPATH) as f:
for line in f.readlines():
items = line.split('\t')
if re.match(items[IDnum], stu):
print(line, end='')
flag = True
if not flag:
print("沒有該% s = %s 的學生信息" % (s, stu))
# 2.增加學生信息
def addMenu():
stu = Student.Stu() #創建對象
while True:#學號 無默認值default
stuID = input("輸入學號ID(001-999):")
p = re.match('^[0-9]{3}$', stuID)#正則表達式 ^匹配開始 $匹配結束 [0-9]{3} 0-9數字匹配三次
if p:
if stuID == '000':
print("學號必須是 001-999")
continue
if isIDExist(stuID, 0):# 0代表的是學號
print("學號 = %s 已存在" % stuID)
continue
else:
stu.set_stuID(stuID)
break
else:
print("學號必須是 001-999")
while True:#姓名 無默認值
name = input("輸入學生姓名:")
#print(type(name)) str類型
#p = re.match(r'^[\u4E00-\u9FFF]+$', 'name') # 正則表達式 ^匹配開始 $匹配結束 匹配多次中文
p = is_Chinese(name)
if p:
stu.set_name(name)
break
else:
print("名字必須為中文")
while True:#性別 默認值default
sex = input("輸入學生性別:(M 男,W 女,默認為M)")
if sex == 'M' or sex == 'm' or sex == '': #包含默認值
stu.set_sex('M')
break
elif sex == 'W' or sex == 'w':
stu.set_sex(sex.upper())
break
else:
print('性別(M/W)')
continue
while True:#班級 默認值
classID = input("輸入學生班級號(01-99,默認為NULL)")
if classID == '':
stu.set_classID('NULL')
break
p = re.match('^[0-9]{2}$', classID)
if p:
if classID == '00':
print("班級號必須為01-99")
continue
stu.set_classID(classID)
break
else:
print("班級號必須為01-99")
file1 = open(FILEPATH, 'a')#打開文件為追加模式
print('ID\t\tNAME\t\tSEX\t\tCLASS')
print(stu.get_stuID()+'\t\t'+stu.get_name()+'\t\t'+stu.get_sex()+'\t\t'+stu.get_classID())
file1.write(stu.get_stuID()+'\t'+stu.get_name()+'\t'+stu.get_sex()+'\t'+stu.get_classID()+'\t'+'\n')
print("增加學生成功")
file1.close()
# 3.刪除學生信息
def delMenu():
print('1.按學號刪除\n2.按班級號刪除')
opt = input("請選擇")
# 備份區
with open(FILEPATH, 'r') as f:
lines = f.readlines()
with open('TEMP.db', 'w') as temp:
temp.writelines(lines)
# 刪除功能
if opt == '1':
delInfoID()
elif opt == '2':
delInfoClassID()
else:
print("輸入錯誤")
# 按學號刪除
def delInfoID():
stuID = input("學號:")
stuIDnum = 0
if not isIDExist(stuID, stuIDnum):
print("學號:%s 不存在" % stuID)
return
# 刪除stuID學生信息
with open(FILEPATH, 'r') as f:
lines = f.readlines()
with open(FILEPATH, 'w') as f_w:
for line in lines:
items = line.split('\t')
if re.match(items[stuIDnum], stuID):
print('學號= %s的學生信息為:\n' % stuID, line)
opt = input("是否確認刪除學號 = %s 的學生信息(Y/N)?" % stuID)
if opt == 'Y' or opt == 'y' or opt == '':
print("刪除成功!")
continue
f_w.write(line)
# 按班級號刪除
def delInfoClassID():
classID = input("班級號:")
classList = []
classNum = 3
if not isIDExist(classID, classNum): # 3代表班級號
print("班級號: %s 不存在" % classID)
return
with open(FILEPATH, 'r') as f:
lines = f.readlines()
with open(FILEPATH, 'w') as f_w:
# 打印要刪除的學生信息
for line in lines:
items = line.split('\t')
if not items[classNum].count(classID) == 0:
classList.append(line)
print('班級號= %s的學生信息為:\n' % classID, '\n'.join(classList))
opt = input("是否確認刪除班級號 = %s 的學生信息(Y/N)?" % classID)
if opt == 'Y' or opt == 'y':
for line in lines:
items = line.split('\t')
if re.match(items[classNum], classID):
continue
f_w.write(line)
print("刪除成功!")
elif opt == 'N' or opt == 'n' or opt == '':
f_w.write(''.join(lines))
else:
print("輸入錯誤,刪除失敗")
f_w.write(''.join(lines))
# 4.修改
def updateMenu():
# 備份區
with open(FILEPATH, 'r') as f:
lines = f.readlines()
with open('TEMP.db', 'w') as temp:
temp.write(''.join(lines))
# 學號唯一
stuID = input("學號:")
stuIDnum = 0
if not isIDExist(stuID, stuIDnum):
print("學號:%s 不存在" % stuID)
return
with open(FILEPATH, 'r') as f:
lines = f.readlines()
with open(FILEPATH, 'w') as f_w:
for line in lines:
items = line.split('\t')
if re.match(items[stuIDnum], stuID):
print('學號= %s的學生信息為:\n' % stuID, line)
continue
f_w.write(line)
# 重新添加學生信息(更新)
stu = Student.Stu() # 創建對象
while True:
stuID = input("輸入新的學號ID(001-999):")
p = re.match('^[0-9]{3}$', stuID)
if p:
if stuID == '000':
print("學號必須是 001-999")
continue
if isIDExist(stuID, 0):
print("學號 = %s 已存在" % stuID)
continue
else:
stu.set_stuID(stuID)
break
else:
print("學號必須是 001-999")
while True:
name = input("輸入新的學生姓名:")
p = is_Chinese(name)
if p:
stu.set_name(name)
break
else:
print("名字必須為中文")
while True: # 性別 默認值default
sex = input("輸入新的學生性別:(M 男,W 女,默認為M)")
if sex == 'M' or sex == 'm' or sex == '':
stu.set_sex('M')
break
elif sex == 'W' or sex == 'w':
stu.set_sex(sex.upper())
break
else:
print('性別(M/W)')
continue
while True: # 班級 默認值
classID = input("輸入新的學生班級號(01-99,默認為NULL)")
if classID == '':
stu.set_classID('NULL')
break
p = re.match('^[0-9]{2}$', classID)
if p:
if classID == '00':
print("班級號必須為01-99")
continue
stu.set_classID(classID)
break
else:
print("班級號必須為01-99")
file1 = open(FILEPATH, 'a') # 打開文件為追加模式
print('ID\t\tNAME\t\tSEX\t\tCLASS')
print(stu.get_stuID() + '\t\t' + stu.get_name() + '\t\t' + stu.get_sex() + '\t\t' + stu.get_classID())
file1.write(stu.get_stuID() + '\t' + stu.get_name() + '\t' + stu.get_sex() + '\t' + stu.get_classID() + '\t' + '\n')
print("修改成功")
file1.close()
# 5.恢復
def backup():
print("1.恢復上一次的學生信息\n2.恢復到系統啟動時學生信息")
opt = input("請輸入:")
if opt == '1':
# 在刪除之后增加的數據也一同恢復
t = open('TEMP.db', 'r+')
lines = t.readlines()
with open(FILEPATH) as f:
for eachLine in f:
if eachLine in lines:
continue
t.write(eachLine)
t.close()
os.remove(FILEPATH)
os.renames('TEMP.db', FILEPATH)
print("恢復成功!")
if opt == '2':
# 將增加的數據也一同恢復
t = open(TEMPFILE, 'r+')
lines = t.readlines()
with open(FILEPATH) as f:
for eachLine in f:
if eachLine in lines:
continue
t.write(eachLine)
t.close()
os.remove(FILEPATH)
os.renames(TEMPFILE, FILEPATH)
shutil.copyfile(FILEPATH, TEMPFILE)
print("成功恢復至啟動時狀態")
# 公共方法
# ***判斷用戶輸入的是否為中文
def is_Chinese(word):
for ch in word:
if '\u4e00' <= ch <= '\u9fff':
return True
return False
# ***判斷學號是否已存在
# ***IDnum代表學號0,姓名1,性別2,班級3等信息
def isIDExist(stuID,IDnum):
flag = False
with open(FILEPATH) as f:
for line in f.readlines():#for line in f:
if stuID in line.strip():
flag = True
return flag '''
b = int(IDnum)
flag = False
with open(FILEPATH) as f:
for line in f:
items = line.split('\t')
if re.match(items[b], stuID):
flag = True
return flag
# 備份系統啟動時的學生信息
def init():
stuBackup = open(TEMPFILE, 'w')
fp = open(FILEPATH, 'r')
stuText = fp.readlines()
stuBackup.write(''.join(stuText))
fp.close()
stuBackup.close()


if __name__ == '__main__':
init()
menuView()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM