Create a program addressbookpy that manages an individuals a
Solution
contacts = {}
def display_menu():
\"Displays the menu options\"
print \"############ MENU ##############\"
print \"1.Add New Contact\"
print \"2.Display Address book\"
print \"3.Search For Contact\"
print \"4.Modify Contact\"
print \"5.Delete Contact\"
print \"6.Exit\"
def search_contact(name):
\"Searches for a given name and return 0 if not found\"
for i in contacts:
if(contacts[i][0] == name):
return i
return 0
def delete_contact():
\"deletes a given contact name\"
name = raw_input(\"Enter name:\");
ind = search_contact(name)
if(ind):
del contacts
print \"Contact Delete successfully\"
else:
print \"Contact Information not found\"
write_to_file()
def modify_contact():
\"modifies a given contact name\"
name = raw_input(\"Enter name:\");
ind = search_contact(name)
if(ind):
print \"Update\ 1.Name\ 2.Address\ 3.Phone\ 4.Email\"
choice = int(input())
if(choice==1):
update = raw_input(\"Name:\")
contacts[ind][0] = update
elif(choice==2):
update = raw_input(\"Address:\")
contacts[ind][1] = update
elif(choice==3):
update = raw_input(\"Phone:\")
contacts[ind][2] = update
elif(choice==4):
update = raw_input(\"Email:\")
contacts[ind][3] = update
else:
print \"Invalid Choice\ \"
else:
print \"Contact Information Not found\"
write_to_file()
def add_new_contact():
\"Adds a new contact to the contact_book\"
name = raw_input(\"Name:\")
address = raw_input(\"Address:\")
phone = raw_input(\"Phone:\")
email = raw_input(\"Email:\");
contacts[len(contacts)+1] = [name,address,phone,email]
write_to_file()
def write_to_file():
\"writes the contact details to a file\"
file = open(\"contact.txt\",\"w\")
for i in contacts:
file.write(\"\ \".join(contacts[i]))
file.write(\"\ \");
file.close();
def read_to_dict():
\"Reads all the contact details to a dict\"
file = open(\"contact.txt\",\"r\")
text = file.read()
textl = text.split(\"\ \")
print textl
factor = 0
contact = []
for i in textl:
if(factor==4):
contacts[len(contacts)+1] = contact
contact = []
contact.append(i)
factor=1
else:
contact.append(i)
factor += 1
file.close()
def display_address_book():
\"Displays all the contact details\"
print \"--------------Address Book-----------------\"
for i in contacts:
display_contact(contacts[i])
print \"----------------------\"
def display_contact(l):
\"Displays a given contact\"
print \"Name : \",l[0]
print \"Address : \",l[1]
print \"Phone : \",l[2]
print \"Email : \",l[3]
read_to_dict() # read all the contats from contact.txt file
while True:
display_menu()
option = int(input())
if(option==1):
add_new_contact()
elif(option==2):
display_address_book()
elif(option==3):
na = raw_input(\"Enter name:\")
ind = search_contact(na)
if(ind):
display_contact(contacts[ind])
else:
print \"Contact Information not found\"
elif(option==4):
modify_contact()
elif(option==5):
delete_contact()
elif(option==6):
break;
else:
print \"Invalid Option\"


