遍历 Pickle 文件中的多个字典

Interate through multiple dictionaries in a Pickle file

我必须使用 pickle 来存储一些数据。我创建了一个 class 来处理数据的 i/o ,其中一个函数负责加载数据并打印所有信息,但是当我调用函数打印数据时,它只通过第一本字典进行交互。所有输入都被保存(当我打开 pickle 文件并且可以看到一些与其他输入相关的数据时)。

我已经检查了一些 Whosebug 问题,例如:Iterating over dictionaries using 'for' loops and 但是 none 的示例给了我预期的输出。

这是负责处理 pickle 的数据库 class:


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}")

这是我为测试 class:

编写的代码
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

正在保存全部信息,当我用文本编辑器打开 pickle 文件时,我可以看到一些存储在那里的信息:

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

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

您可以在 pickle 之前尝试组合这两个词典,但这可能不是您特定应用程序想要的。我的猜测是 db.printfile().load 部分没有加载两个词典,因此只是 printing/returning 第一个。

您可以对同一个文件多次 运行 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