Python--将字典写进文件 ,增删改查练习

a={
    '001':{'name':'张三','age':18,'address':'北京'},
    '002':{'name':'张二','age':28,'address':'上海'},
    '003':{'name':'张大','age':38,'address':'北京'},
    '004':{'name':'张四','age':28,'address':'上海'},
    '005':{'name':'张六','age':39,'address':'北京'}
}

class StudentAdmin():
    @staticmethod
    def write():
        f=open('a.txt','w')
        f.write(str(a))
        f.close()
    @staticmethod
    def read():
        f=open('a.txt','r')
        c=f.read()
        f.close()
        return eval(c)

a = StudentAdmin.write()
a=StudentAdmin.read()

while True:
    print('操作编号:','1:添加','2:删除','3:修改','4,:查找','5:退出程序')
    bh=int(input('请选择要进行的操作:'))
    if bh==1:
        xh=input('请输入要添加的学号:')
        if xh in a.keys():
            print('学号重复,添加失败')
            continue
        else:
            zd={}
            zd['name']=input('请输入要添加的姓名:')
            zd['age']=int(input('请输入要添加的年龄:'))
            zd['address']=input('请输入要添加的地址:')
            a[xh]=zd
        print(a)
    elif bh==2:
        xh=input('请输入要删除的学号:')
        if xh not in a.keys():
            print('查无此人,删除失败')
            continue
        else:
            print('要删除的人是:',a[xh])
            del a[xh]
            print(a)
    elif bh==3:
        xh=input('请输入要修改的学号:')
        if xh not in a.keys():
            print('查无此人,修改失败')
            continue
        else:
            a[xh]['name']=input('请输入修改后的姓名:')
            a[xh]['age']=int(input('请输入修改后的年龄:'))
            a[xh]['address']=input('请输入修改后的地址:')
            print(a)
    elif bh==4:
        xh=input('请输入要查找的学号:')
        if xh not in a:
            print('查无此人,查找失败')
            continue
        else:
            print(a[xh])
    elif bh==5:
        a = StudentAdmin.write()
        break

猜你喜欢

转载自blog.csdn.net/bzzb_/article/details/88562544
0条评论
添加一条新回复