-1

i want to save keys and values in dictionary and use it tomorrow or next week i have read book "A byte of Python" I want to do questions from book, but i don't understand how work pcikle with dictionaryes

import os
import pickle

addressbook = {}
home = os.environ['HOME']
path = home + '/.local/share/addressbook'
addressbookfile = path + '/' + 'addressbook.data'
if not os.path.exists(path):
    os.mkdir(path)
    
while True:
    print("What to do?: ")
    print("1 - full list")
    print("2 - add a contact")
    print("3 - remove contact")

    answer = int(input("Number of answer: "))

    if answer == 1:
        f = open(addressbookfile, 'rb')
        storedlist = pickle.load(f)
        print(storedlist)
    elif answer == 2:
        namecontact = str(input("Enter the name of cantact: "))
        name = str(input("Enter the name: "))
        lastname = str(input("Enter the lastname: "))
        number = int(input("Enter the number: "))
        addressbook[namecontact] = [name, lastname, number]
        f = open(addressbookfile, 'wb')
        pickle.dump(addressbookfile, f)
        f.close()
metah
  • 1
  • The reason why that's not working is the line where you say `pickle.dump(addressbookfile, f)`. This is pickling the filepath, not the dictionary. Try replacing `addressbookfile` with `addressbook`. – linux_kettle Aug 21 '20 at 06:24
  • You pickle the `addressbookfile`, not the `addressbook`. – Niklas Mertsch Aug 21 '20 at 06:28
  • Welcome to Stack Overflow. Please read [how to ask a good question](https://stackoverflow.com/help/how-to-ask) from the Help pages. For this question you need to create a [mre], which will help yourself understand the problem better, and it helps us help you with the problem. – wovano Aug 21 '20 at 06:30
  • Also, did you already search for a solution on Stack Overflow? This seems a basic question and there are already a lot of answers. I recently wrote [this answer](https://stackoverflow.com/a/63457062/10669875) to demonstrate the use of pickle. – wovano Aug 21 '20 at 06:32

1 Answers1

0

Python pickle serialises and deserialises objects and can be used to save variables to file for later use.

As you do, the variables are saved with

pickle.dump(addressbook , f)

You can the load the data with

addressbook = pickle.load(f)

Where f is your file handle