永久存储要在字典中使用的值

时间:2016-07-16 05:51:45

标签: python python-3.x

我的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)]
`

以及我和#34;的顺序"这些对象是通过调用我的订单类中的函数

    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值并正确显示,唯一的问题是如果我终止程序它不会存储我何时打开它的数据。如果我要永久存储数据,我该怎么做?我应该永久存储什么?

1 个答案:

答案 0 :(得分:1)

因此,您可以使用python将任何pickle对象保留在文件中。因此,假设您要保留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.total调用)后存储order。并且,在您首次声明self.total的类的初始值设定项中,您需要使用从pickle文件加载的字典(如果存在)初始化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)

initializer类的Order

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以重置。

希望有所帮助:)