【问题标题】:What i need to use pickle for save dictionary我需要用泡菜来保存字典
【发布时间】: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的使用。

标签: python pickle


【解决方案1】:

Python pickle 序列化和反序列化对象,并可用于将变量保存到文件以供以后使用。

正如你所做的那样,变量保存在

pickle.dump(addressbook , f)

你可以加载数据

addressbook = pickle.load(f)

f 是你的文件句柄

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多