学生系统的删除
delete()函数的设计
def delete():
while True:
student_id=input('请输入要删除的学生ID:')
if student_id!='':
if os.path.exists(filename):
with open(filename,'r',encoding='utf-8') as file:
student_old=file.readlines()
else:
student_old=[]
flag=False #标记是否删除
if student_old:
with open(filename,'w',encoding='utf-8') as wfile:
d={}
for item in student_old:
d=dict(eval(item)) #将字符串转成字典
if d['id']!=student_id:
wfile.write(str(d)+'\n')
else:
flag=True
if flag:
print(f'id为{student_id}的学生信息一杯删除')
else:
print(f'没有找到ID为{student_id}的学生信息')
else:
print('无学生信息')
break
show() #删除后要重新显示所有学生信息,调用个函数
answer=input('是否继续删除?y/n\n')
if answer=='y':
continue
else:
break
完全按照老师讲的,打了所有的代码,但是一直报错!!!!
出来的提醒是
File "<string>", line 1
后来查到相关的事 eval函数的问题
也就是写入了字符串,少了{}字典的数据
d=dict(eval(item)) #将字符串转成字典
重新修改了还是不行,只是显示item并非字典!
for item in student_old
item只是在重复带入student_old的数据,student_old不是字典?
就在这个地方查出了问题,原来的代码是
student_old=file.readline() 这是错误的.
正确的应该是student_old=file.readlines()
file.readline,只读取了单行,student_old只能读取首行的数据
而file.readlines读取了很多行,才能确保student_old写入所有的数据
绕了一大圈,居然问题出在这个地方