通过Pickle文件中的多个词典进行交互

时间:2019-05-29 00:14:05

标签: python python-3.x dictionary pickle python-3.7

我必须使用泡菜来存储一些数据。我创建了一个用于处理数据I / O的类,该函数可用于加载数据并打印所有信息,但是当我调用该函数以打印数据时,它仅在第一个字典中进行插入。所有输入都被保存(当我打开pickle文件时,可以看到一些与其他输入相关的数据)。

我检查了一些stackoverflow问题,例如:Iterating over dictionaries using 'for' loopsBest way to loop through multiple dictionaries in Python,但是没有一个示例给我期望的输出。

这是可用于处理泡菜的DataBase类:


import pickle
from pathlib import Path

class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            return loaded_file

    def PrintFile(self):
        for k, v in self.Load().items():
            print(f"{k} {v}")

这是我为测试该类而编写的代码:

from DataBase import DataBase as DB

dict0 = {1:'A', 2:'E', 3:'I', 4:'O', 5:'U'}
dict1 = {0:"Water", 1:"Fire", 2:"Air", 3:"Sand"}
db = DB("test")
db.Create(dict0)
db.Create(dict1)
db.PrintFile()

我希望输出为:

1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand

但是我得到的输出是:

1 A 
2 E
3 I 
4 O 
5 U

所有信息都被保存了,当我打开带有文本ediot的pickle文件时,我可以看到一些存储在其中的信息:

��#}�(K�A�K�E�K�I�K�O�K�U�u.��)}�(K�Water�K�Fire�K�Air�K�Sand�u
例如,我们可以在文件中看到Air。

我应该怎么做才能获得预期的输出?

2 个答案:

答案 0 :(得分:1)

您可以在同一文件上多次运行pickle.load()。

赞:

import pickle
from pathlib import Path


class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            loaded_file2 = pickle.load(this_file)
            return [loaded_file, loaded_file2]

    def PrintFile(self):
        for i in self.Load():
            for k, v in i.items():
                print(f"{k} {v}")


if __name__ == '__main__':
    # from DataBase import DataBase as DB
    dict0 = {1: 'A', 2: 'E', 3: 'I', 4:'O', 5: 'U'}
    dict1 = {0: "Water", 1: "Fire", 2: "Air", 3: "Sand"}
    db = DataBase("test")
    db.Create(dict0)
    db.Create(dict1)
    db.PrintFile()

给出以下输出:

1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand

答案 1 :(得分:-1)

您可以在腌制两个字典之前尝试将它们组合在一起,但这可能不是特定应用程序想要的。我的猜测是.load的{​​{1}}部分没有加载两个字典,因此仅打印/返回第一个。