简体   繁体   中英

What i need to use pickle for save dictionary

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM