辞書を保存するためにpickleを使用する必要があるもの

Aug 21 2020

キーと値を辞書に保存して明日または来週使用したい本「Pythonのバイト」を読んだ本から質問をしたいのですが、辞書でpcikleがどのように機能するのかわかりません

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

回答

L.S.Harbo Aug 21 2020 at 13:32

Python pickleはオブジェクトをシリアル化および逆シリアル化し、後で使用するために変数をファイルに保存するために使用できます。

あなたがするように、変数はで保存されます

pickle.dump(addressbook , f)

あなたはでデータをロードすることができます

addressbook = pickle.load(f)

ここで、fはファイルハンドルです。