[英]What i need to use pickle for save dictionary
我想在字典中保存键和值并在明天或下周使用它 我读过书“A byte of Python”
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 是您的文件句柄
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.