Pickling适用于Python2,但不适用于Python3

时间:2017-03-04 19:49:16

标签: python python-2.7 python-3.x pickle

我的目标是将字典对象序列化到特定的文件位置,并在每次运行程序时将其读回。以下适用于Python2.7,但在Python3.4中引发错误。令我困惑的是,这在第一次将对象保存到磁盘时起作用,但在后续执行时却不起作用。

问题似乎是在 setitem 中出现了一个错误,表示“' ConfigDict'对象没有属性' _config_file'。除了第一次运行脚本之外,为什么它没有任何值?

strcpy(out, in)

这里是完整的追溯:

import os
import pickle


class ConfigDict(dict):

    def __init__(self, config_name): # Name of a pickle file within configs directory
        self._config_directory = 'C:\\Users\\myfilepath\\configs'
        self._config_file = self._config_directory + '\\' + config_name + '.pickle'
        # If file does not exist, write a blank pickle file.
        if not os.path.isfile(self._config_file):
            with open(self._config_file, 'wb') as fh:
                pickle.dump({}, fh)
        # Read the pickle file from disk.
        with open(self._config_file, 'rb') as fh:
            pkl = pickle.load(fh)
            self.update(pkl)

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        with open(self._config_file, 'wb') as fh:
            pickle.dump(self, fh)


cc = ConfigDict('DBConfig')
print()
print()
cc['config_val_1'] = '1'
cc['config_val_3'] = '3'
print(cc['config_val_3'])

0 个答案:

没有答案