import os

data = []

def read_file():
    if os.path.exists('data.txt'):
        with open("data.txt") as f:
            try:
                for line in f:
                    (name, phone) = line.split()
                    entry = {'name': name, 'phone': phone}
                    data.append(entry)
            except:
                print "error"

def write_file():
    with open("data.txt", 'w') as f:
        for entry in data:
            line = entry['name'] + ' ' + entry['phone'] + '\n'
            f.write(line)

def display_contacts():
  for index, contact in enumerate(data):
    print(index+1, contact['name'], contact['phone'])

def add_contact(name, phone):
  contact = {'name': name, 'phone': phone}
  data.append(contact)

def remove_contact(name_index):
    data.pop(name_index-1)
        
read_file()
print("Phone Book")
while True:
  print()
  print("Choose your option")
  print("1. List contacts")
  print("2. Add contact")
  print("3. Remove contact")
  print("Press q to exit")
  choice = raw_input("")
  os.system('clear')
  if choice == 'q':
    break
  if choice == '1':
    display_contacts()
  elif choice == '2':
    name = raw_input("Name: ")
    phone = raw_input("Phone: ")
    add_contact(name, phone)
  elif choice == '3':
    name_index = int(input("Which contact to remove? Enter number: "))
    os.system('clear')
    if (1 <= name_index <= len(data)):
        remove_contact(name_index)
    else:
        print "Sorry index not in contacts!"
  else:
    print "I dont undestand?"

write_file()
