Sorted function in python writing to a file

3276 views python
-4

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()))
    phonebook.write(contact)
    phonebook.close  

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

3

import pickle
f = open("file.pkl","wb") 
pickle.dump(dict,f) 
f.close()

https://i.stack.imgur.com/ZDVVZ.png check Here

posted this
12

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?

JD

Please login first before posting an answer.