【发布时间】:2020-08-21 06:22:31
【问题描述】:
我想将键和值保存在字典中,明天或下周使用 我已经阅读了“A byte of 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()
【问题讨论】:
-
这不起作用的原因是你说
pickle.dump(addressbookfile, f)的那一行。这是腌制文件路径,而不是字典。尝试将addressbookfile替换为addressbook。 -
你腌制的是
addressbookfile,而不是addressbook。 -
欢迎来到 Stack Overflow。请阅读帮助页面中的how to ask a good question。对于这个问题,您需要创建一个minimal reproducible example,这将有助于您更好地了解问题,并帮助我们帮助您解决问题。
-
另外,您是否已经在 Stack Overflow 上搜索过解决方案?这似乎是一个基本问题,并且已经有很多答案。我最近写了this answer来演示pickle的使用。