python 教程 第十四章、 地址薄作业

第十四章、 地址薄作业

#A Byte of Python
#!/usr/bin/env python
import cPickle
import os 
#define the contacts file, list
global file_contacts
global list_contacts
file_contacts = 'AddressBook.txt'
list_contacts = [] 
#delete the file
try:
    file_path = os.getcwd() + os.sep + file_contacts
    if os.path.isfile(file_path):
        os.remove(file_contacts)
        f = file(file_contacts,'w')
        f.close() 
     #define the class of contacts and implement the methods
    class class_contacts:
        def __init__(self, list_contacts):
            self.contacts = list_contacts
        def append(self, name, mail):
            dict_contacts = {'Name': name, 'Mail': mail}
            self.contacts.append(dict_contacts)
        def find(self, name):
            found = False
            for instance_contacts in list_contacts:
                if name == instance_contacts['Name']:
                    found = True
                    print " Found:", name, ", PASS"
                    break
            if not found:
                print " Found:", name, ", FAIL" 
        def modify(self, name, mail):
            for instance_contacts in list_contacts:
                if name == instance_contacts['Name']:
                    instance_contacts['Mail'] = mail
                    break
        def delete(self, name):
            index = -1
            for instance_contacts in list_contacts:
                index += 1
                if name == instance_contacts['Name']:
                    del list_contacts[index]
        def show(self):
            for list in list_contacts:
                print list
        def save(self):
            fa = file(file_contacts, "a")
            cPickle.dump(self.contacts, fa)
            fa.close() 
    i = class_contacts(list_contacts)
    i.append('joan', 'joan@123.com')
    i.append('adny', 'adny@123.com')
    i.append('xixi', 'xixi@123.com')
    i.find('joan')
    i.find('joab')
    print "Original List:"
    i.show()
    print "after modify adny"
    i.modify('adny', 'adnX@123.com')
    i.show()
    print "after del joan"
    i.delete('joan')
    i.show()
    i.save() 
except TypeError:
    print "TypeError"
except:
print "Other Error occured" 

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值