In Python: Using Python create a function that saves the contacts database to a
ID: 640420 • Letter: I
Question
In Python:
Using Python create a function that saves the contacts database to a file. The "save" function should take one argument (the contacts database). With a loop, you can save each name and e-mail address, line by line. You're probably going to want to read two lines at a time (one name, one email) and then add what you've read to the contacts dictionary. Then, you keep doing it until you're done with the file.
Note that readline returns the line with a newline character (' ') at the end. We need to get rid of that. That's why the code above has a .strip() added to it.
What happens when you've read all the lines in the file?Then, the readline function will return an empty string. You can check that and end your loop.
Here is the code --------------------
Explanation / Answer
def save(contacts):
f=open("contacts.txt","w") #contacts.txt file name
for key in contacts.keys(): # iterating through the contacts dictionary by keys
f.write(key) #saving the key to file i.e. the name
f.write(contacts[key]) #saving the value of key to file i.e. the email
print #separator to the names and emails
f.close() #after the loop ends the file is closed
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.