Sorted function in python writing to a file

3276 views python

The task:

Your program should read from the file, storing the names and corresponding email addresses in a dictionary as key-value pairs. Then, the program should display a menu that lets the user enter the numbers 1 through 5, each corresponding to a different menu item: When the user enters 5, the program should write the names and email addresses in alphabetical order by first name to the file phonebook.out You can use the sorted() function which accepts a dictionary argument to sort a dictionary based on Key

This is my code:

def write_to_file(contact):
    file = open("phonebook.out", "w")
    contactsort = dict(sorted(contact.items()))

However, this code isn't working. I'm not sure why, so any help is appreciated. thank you.

answered question

What do you mean by "isn't working"?, do you get an error?,

no it doesn't show any error.

Why do you define file = ... but then use phonebook to write out your data?

So should it be file.write? When I change phonebook to file, it highlights file and says invalid syntax.

It should be the file object where you're trying to store your data. In your code phonebook isn't declared anywhere, so I don't know where it comes from and what it means. Anyway, use with open('phonebook.out', 'w') as file and then file.write(...) for working with files. Check docs

2 Answers


import pickle
f = open("file.pkl","wb") 
f.close() check Here

posted this

Have you tried json file? Like this:

import json
filename = "phonebook.json"
def write_to_file(contact):
    with open(filename, 'w') as f_obj:
        contactsort = dict(sorted(contact.items()))
        json.dump(contact, f_obj)

posted this

Have an answer?


Please login first before posting an answer.