37,719
社区成员
发帖
与我相关
我的任务
分享
import pickle as p
import os, sys
class AddressBook:
# 'ab' is short for 'a'ddress'b'ook
# sample: ab = {welon : [15012345678, chinawelon@gmail.com]}
ab = {}
def __init__ (self, name, telephone, email):
'''Initializes the contact's data'''
self.name = name
self.telephone = telephone
self.mail = email
@staticmethod
def save(ab):
'''save one's information to file'''
with open(contact_list, mode = 'a', encoding = 'utf-8') as f:
p.dump(ab, f)
def add_contact(self):
'''add a new contact'''
print("Input new contact information:")
print("Input name:")
self.name = input()
print("Input telephone:")
self.telephone = input()
print("Input E-mail:")
self.mail = input()
ab[self.name][0] = self.telephone
ab[self.name][1] = self.mail
print("Add {0} successfully".format(self.name))
AddressBook.save(ab)
def show_contact(self):
'''output one's information'''
print ("{0}'s telephone is: {1} and E-mail is: {2}\n\n".format(
self.name, self.telephone, self.mail))
@staticmethod
def seach_contact(name):
'''Iteration search'''
with open(contact_list, mode = 'rb', encoding = 'utf-8') as f:
stored_list = p.load(f)
if stored_list[name]:
print ("{0}'s telephone is: {1} and E-mail is: {2}\n\n".format(
name, stored_list[name][0], stored_list[name][1]))
else:
print('sorry, {0} was not in the Contact book!'.format(name))
@staticmethod
def delete_contact(name):
with open(contact_list, mode = 'wb', encoding = 'utf-8') as f:
stored_list = p.load(f)
if stored_list[name]:
del stored_list[name]
p.dump(stored_list, f)
else:
print('sorry, {0} was not in the Contact book!'.format(name))
'''____________main____________'''
while True:
contact_list = 'contact.data'
if sys.argv[1].startswith('-'):
option = sys.argv[1][1:]
if option == 'version':
print('Version 1.2')
elif option == 'help':
print('''\
You can input options as follow:
-version : Prints the Version number
-help : Display this help
-add : Add a contact to AddressBook
-del : Delete a contact from AddressBook
-search : Find a person from AddressBook ''')
elif option == 'add':
a = AddressBook(sys.argv[2], sys.argv[3], sys.argv[4])
a.add_contact()
a.show_contact()
a.save(a.ad)
elif option == 'del':
print("Input the name of contacts you want to delete:")
name = input()
delete_contact(name)
elif option == 'search':
print("Input the name of contacts you want to search: ")
name = input()
seach_contact(name)
else:
print("Unknown option")
sys.exit()