Python联系人(添、删、查、改)

来源:互联网 发布:金融大数据应用案例 编辑:程序博客网 时间:2024/06/16 01:48
#!/usr/bin/python#gavinlu1015@gmail.com#linux OSimport pickleimport osfile='contact.data'contact={}class ContactInfo:    def __init__(self, name, relationship, phonenum):        self.name = name        self.relationship = relationship        self.phonenum = phonenum        print('name: {0} - relationship: {1} - phonenum {2}'                .format(self.name, self.relationship,                     self.phonenum))class ContactOper:    def PersonAdd(self, ContactInfo):        f = open(file, 'rb')        contact = pickle.load(f)        contact[ContactInfo.name] = ContactInfo        f.close()        f = open(file, 'wb')        pickle.dump(contact, f)         f.close()        print('Add: {0}' .format(ContactInfo.name))    def PersonDel(self, name):        f = open(file, 'rb')        contact = pickle.load(f)        del contact[name]        f.close()        f = open(file, 'wb')        pickle.dump(contact, f)         f.close()        print('del: {0}' .format(name))    def PersonShow(self):        f = open(file, 'rb')        contact = pickle.load(f)        f.close()        for name, contactinfo in contact.items():            print('name:{0} contact:{1} phonenum:{2}'                .format(name, contactinfo.relationship,                    contactinfo.phonenum))    def PersonRepair(self, rname, relationship, phonenum):        f = open(file, 'rb')        contact = pickle.load(f)        f.close()        for name, contactinfo in contact.items():            if(name == rname and (relationship or phonenum)):                contact[rname].relationship = relationship                contact[rname].phonenum = phonenum        f = open(file, 'wb')        pickle.dump(contact, f)         f.close()while(True):    t = raw_input('A:add D:del S:show R:repair Q:quit\n')    if not os.path.exists(file):          f = open(file, 'w')        f.write("(dp0\n.")        f.close()    if(t == 'A'):        print('Please input contact info')        n = raw_input('name:')        c = raw_input('contact:')        p = raw_input('phonenum:')        t = ContactInfo(n, c, p)        h = ContactOper()        h.PersonAdd(t)    elif(t == 'D'):        print('Please input contact name\n')        n = raw_input('name:')        h = ContactOper()        h.PersonDel(n)    elif(t == 'S'):        h = ContactOper()        h.PersonShow()    elif(t == 'R'):        n = raw_input('Please input repair contact name:')        c = raw_input('contact:')        p = raw_input('phonenum:')        h = ContactOper()        h.PersonRepair(n, c, p)    elif(t == 'Q'):        print('exiting now ...')        exit()    else:        print('input error!')        continue
0 0
原创粉丝点击