import pickle
from functools import reduce # reduce import
def load_file(): # 저장되어있는 파일 불러오기
table = dict()
try:
with open('table.p', 'rb') as file:
table = pickle.load(file)
print('파일 불러오기 성공')
except FileNotFoundError as e:
print('파일이 없습니다.')
return table
def disp_score(**kwagrs): # 점수 출력 함수
for name, score in kwagrs.items():
total = reduce(lambda x, y: x + y, score.values()) # 총점 람다식
print('이름 : ', name)
print('국어 : ', score.get('국어'))
print('영어 : ', score.get('영어'))
print('수학 : ', score.get('수학'))
print('과학 : ', score.get('과학'))
print('총점 : ', total)
print('평균 : ', (lambda x, y: x / y)(total, len(score))) # 평균 람다식
print()
def hasName(name, **kwagrs): # 해당 이름 검사 함수
hasName = {key:value for key, value in kwagrs.items() if key==name} # 넘어온 이름으로 딕셔너리 표현식
return hasName
while True:
chk = int(input('1.추가 2.검색 3.삭제 4.수정 5.출력 : '))
# 추가
if chk == 1:
table = load_file() # 파일을 불러옴
name = input('학생 이름 : ')
NameCheck = hasName(name, **table) # 이름 비교
if NameCheck == {}: # 해당 이름이 없을 때
score = dict(zip(['국어', '영어', '수학', '과학'], list(map(int, input('점수 : ').split()))))
table.setdefault(name, score) # table 딕셔너리에 키-값 저장
with open('table.p', 'wb') as file:
pickle.dump(table, file) # table.p 파일에 바이너리 쓰기모드로 작성
else:
print('해당 학생 이름이 존재합니다.')
# 검색
elif chk == 2:
name = input('이름을 입력하세요 : ')
table = load_file() # 파일 불러옴
if table != {}:
NameCheck = hasName(name, **table) # 이름 비교
if NameCheck != {}: # 해당 이름이 있을 때
disp_score(**NameCheck) # 점수 출력
else:
print('해당 학생이 존재하지 않습니다.')
else:
print('학생 정보가 없습니다.')
# 삭제
elif chk == 3:
name = input('이름 : ')
table = load_file() # 파일 불러옴
if table != {}:
NameCheck = hasName(name, **table) # 이름 비교
if NameCheck != {}: # 해당 이름이 있을 때
table = {key:value for key, value in table.items() if key != name} # 해당 키가 없는 상태로 딕셔너리를 만듬
with open('table.p', 'wb') as file:
pickle.dump(table, file) # talbe.p파일에 바이너리 쓰기모드로 작성
else:
print('해당 학생이 존재하지 않습니다.')
else:
print('학생 정보가 없습니다.')
# 수정
elif chk == 4:
name = input('이름 : ')
table = load_file() # 테이블 불러옴
if table != {}:
NameCheck = hasName(name, **table) # 이름 비교
if NameCheck != {}: # 해당 이름이 있을 때
score = dict(zip(['국어', '영어', '수학', '과학'], list(map(int, input('점수 : ').split()))))
table.update({name : score}) # table에 값을 수정함
with open('table.p', 'wb') as file:
pickle.dump(table, file) # table.p에 바이너리 쓰기모드로 작성
else:
print('해당 학생이 존재하지 않습니다.')
else:
print('학생 정보가 없습니다.')
# 출력
elif chk == 5:
table = load_file() # 파일 불러옴
if table != {}: # 파일이 있는지 확인
disp_score(**table) # 전체 출력
else:
print('학생 정보가 없습니다.')
else:
print('프로그램을 종료합니다.')
break
반응형
'Python > Python 연습' 카테고리의 다른 글
(Python) 날씨 API 활용 (0) | 2020.11.12 |
---|---|
(Python) 제주도 교통정보 일간 통계 API로 값 뽑기 (0) | 2020.11.12 |
(Python) Selenium 연습 : 로그인, 검색 (0) | 2020.11.09 |
(Python) 데이터 시각화 연습 : 웹에서 값 가져오기 (0) | 2020.11.04 |
(Python)성적관리 프로그램 (0) | 2020.10.14 |