Python 实现读书管理系统
"""
实现一个命令行版的读书管理系统
"""
import os. path
import sys
students = [ ]
def save ( ) :
"""
用于存档,将内存保存到文件中
:return:
"""
with open ( './resource.txt' , 'w' , encoding= 'utf8' ) as file :
for stu in students:
file . write( f" { stu[ 'studentId' ] } \t { stu[ 'name' ] } \t { stu[ 'gender' ] } \t { stu[ 'className' ] } \n" )
print ( f"[存档成功] 共储存了 { len ( students) } 条记录!" )
def load ( ) :
"""
用于读档
:return:
"""
if not os. path. exists( './resource.txt' ) :
return
global students
students = [ ]
with open ( './resource.txt' , 'r' , encoding= 'utf8' ) as file :
for line in file :
line = line. strip( )
splitList = line. split( '\t' )
if len ( splitList) != 4 :
print ( f'当前格式存在问题, line= { line} ' )
continue
student = {
'studentId' : splitList[ 0 ] ,
'name' : splitList[ 1 ] ,
'gender' : splitList[ 2 ] ,
'className' : splitList[ 3 ]
}
students. append( student)
print ( f"[读档成功] 共读取了 { len ( students) } 条记录" )
def menu ( ) :
print ( '-----------------------------------------' )
print ( ' 1.新增学生 ' )
print ( ' 2.显示学生 ' )
print ( ' 3.查找学生 ' )
print ( ' 4.删除学生 ' )
print ( ' 0.退出程序 ' )
print ( '-----------------------------------------' )
choice = input ( ' 请输入您的选择:' )
return choice
def insert ( ) :
print ( '[新增学生]开始!' )
studentId = int ( input ( '请输入学生学号:' ) )
name = input ( '请输入学生的姓名:' )
gender = input ( '请输入学生的性别:' )
if gender not in [ '男' , '女' ] :
print ( '性别输入内容不符合要求' )
return
className = input ( '请输入学生班级' )
student = {
'studentId' : studentId,
'name' : name,
'gender' : gender,
'className' : className
}
global students
students. append( student)
save( )
print ( '[新增学生]完毕!' )
def display ( ) :
print ( '[显示学生] 开始!' )
for stu in students:
print ( f" { stu[ 'studentId' ] } \t { stu[ 'name' ] } \t { stu[ 'gender' ] } \t { stu[ 'className' ] } " )
print ( f'[显示学生] 完毕,共显示了 { len ( students) } 条记录' )
def find ( ) :
print ( '[查找学生] 开始!' )
name = input ( '请输入要查找的学生姓名' )
count = 0
global students
for stu in students:
if stu[ 'name' ] == name:
print ( f" { stu[ 'studentId' ] } \t { stu[ 'name' ] } \t { stu[ 'gender' ] } \t { stu[ 'className' ] } " )
count += 1
print ( f'[查找学生] 完毕, 共匹配到 { count} 条记录' )
def delete ( ) :
print ( '[删除学生] 开始' )
studentId = input ( '请输入要删除学生的学号:' )
global students
for stu in students:
if stu[ 'studentId' ] == studentId:
print ( f"删除 { stu[ 'name' ] } 同学的信息!" )
students. remove( stu)
save( )
print ( '[删除学生] 结束' )
def main ( ) :
"""
入口函数
:return:
"""
print ( '--------------------------------------------' )
print ( ' 欢迎来到学生管理系统' )
print ( '--------------------------------------------' )
load( )
while True :
chioce = menu( )
if chioce == '1' :
insert( )
elif chioce == '2' :
display( )
elif chioce == '3' :
find( )
elif chioce == '4' :
delete( )
elif chioce == '0' :
print ( 'goodbye!' )
sys. exit( 0 )
else :
print ( '输入有误,请重新输入' )
main( )