我需要用泡菜保存字典



我想把键和值保存在dictionary中,明天或下周使用我读过一本书;Python的一个字节";我想做书中的问题,但我不明白如何使用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序列化和取消序列化对象,可用于将变量保存到文件中以备将来使用。

正如您所做的那样,变量是用保存的

pickle.dump(addressbook , f)

你可以用加载数据

addressbook = pickle.load(f)

其中f是您的文件句柄

最新更新