【问题标题】:permanently store a value to be used in a dict [duplicate]永久存储要在字典中使用的值[重复]
【发布时间】:2016-11-19 09:05:15
【问题描述】:

我的 Order 类中有一个字典 self.total = defaultdict(int),用于输入和打印在我的订购系统中订购的每件商品的总数。对象存储为

coffee_available=[Coffee(1, "1: Flat White", 3.50), 
            Coffee(2, "2: Long Black", 3.50), 
            Coffee(3, "3: Cappuccino", 4.00), 
            Coffee(4, "4: Espresso", 3.25), 
            Coffee(5, "5: Latte", 3.50)]
`

我“订购”这些对象的方式是在我的订单类中调用一个函数

    def order(self, order_amount, coffee_id):

        self.total[coffee_id] += order_amount

我使用订单类中的另一个函数打印每个项目类型及其各自的订单金额

def print_order(self):
    print(" ")
    print("Coffee Type\t\tAmount of Times ordered")                       
    print("-----------\t\t-----------------------")
    for coffee in coffee_available:

        print("{}\t- - -\t {} ".format(coffee.coffee_type,   self.total[coffee.coffee_id]))

这很好用,因为每次我的代码在同一个会话中运行时,它每次都会存储order_amount 值并正确显示它,唯一的问题是,如果我终止程序,它不会存储何时的数据我接下来打开它。如果我要永久存储数据,我会怎么做?我应该永久存储什么?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

因此,您可以使用pickle 使任何python 对象持久保存在文件中。所以假设你想坚持total

import pickle
# total is a dictionary
# to store it in a file
with open('total_dictionary.pickle', 'wb') as handle:
  pickle.dump(total, handle)

# lets say program terminated here

现在,

# to load it, if it was previously stored
import pickle
with open('total_dictionary.pickle', 'rb') as handle:
  total = pickle.load(handle)

# total dictionary is exactly same even if the program terminated.

所以,您的 order 方法会更新您的 self.totalprint_order 只是查看它。所以基本上你需要在每次更新后存储self.totalorder 调用)。而且,在您首先声明self.total 的类的初始化程序中,您需要使用从腌制文件(如果存在)加载的字典来初始化self.total


再具体一点:

import pickle
..
def order(self, order_amount, coffee_id):
    self.total[coffee_id] += order_amount
    with open('total_dictionary.pickle', 'w') as handle:
        pickle.dump(total, handle)

initializerOrder 类中

import os
..
def __init__(self):
    ...
    if os.path.exists("total_dictionary.pickle"):
        with open('total_dictionary.pickle', 'r') as handle:
            total = pickle.load(handle)
    else:
        total = defaultdict(int)
    ...

您可以删除/删除total_dictionary.pickle 进行重置。

希望对你有帮助:)

【讨论】:

  • 所以我使用pickle的方式是将值存储在self.total dict中,稍后需要调用order函数时调用它
  • order 函数更新self.totalprint_order 访问它。所以你需要做的就是:在每次更新调用之后,即order调用使用pickle将total字典存储在文件中。在类的初始化程序中,确保如果存在腌制文件,则使用该字典初始化总。酷吗?
  • 感谢您的帮助,现在可以正常使用了。它不存储第一个订单,但没关系
  • 你的更新会抛出这个错误 'AttributeError: module 'ntpath' has no attribute 'exist'
  • 已更新。错误是函数是os.path.exists 而不是os.path.exist。复数's'。还要确保你已经导入了 os 模块。
猜你喜欢
  • 2012-08-03
  • 2017-08-15
  • 2015-01-01
  • 2022-12-31
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 2021-06-12
  • 2021-03-15
相关资源
最近更新 更多