I have a file with a bunch of names and emails. They are written as follows:
name
email
name
email
I cant figure out how to open the file and read line by line to where it pairs "name to email" in my dictionary
I got the code to work when I manually type in the names/emails into the dictionary but I need to pull it from the file.
LOOK_UP=1
ADD= 2
CHANGE= 3
DELETE=4
QUIT=5
def main():
emails={}
with open('phonebook.in') as f:
for line in f:
(name, email)=line.split
emails[name]=email
choice=0
while choice !=QUIT:
choice= get_menu_choice()
if choice == LOOK_UP:
look_up(emails)
elif choice == ADD:
add(emails)
elif choice == CHANGE:
change(emails)
elif choice == DELETE:
delete(emails)
def get_menu_choice():
print('Enter 1 to look up an email address')
print('Enter 2 to add an email address')
print('Enter 3 to change an email address')
print('Enter 4 to delete an email address')
print('Enter 5 to Quit the program')
print()
choice= int(input('Enter your choice: '))
while choice <LOOK_UP or choice >QUIT:
choice= int(input('Enter a valid choice'))
return choice
def look_up(emails):
name= str(input('Enter a name: '))
value=(emails.get(name, 'Not found.'))
print(value)
print()
def add(emails):
name= str(input('Enter a name: '))
emailsaddy= input(' Enter a email address: ')
if name not in emails:
emails[name]= emailsaddy
print()
else:
print('That contact already exists')
print()
def change(emails):
name=str(input ('Enter a name: '))
if name in emails:
emailsaddy= str(input(' Enter a new email: '))
emails[name]= emailsaddy
else:
print('That contact does not exist')
def delete(emails):
name=str(input ('Enter a name: '))
if name in emails:
del emails[name]
else:
print('That contact is not found')
main()