我有一个字典,我想序列化和反序列化:
dict = {
datetime.datetime.strptime('2016-10-01', '%Y-%m-%d'): {
'product1': 3300.00,
},
datetime.datetime.strptime('2016-10-05', '%Y-%m-%d'): {
'product1': 3000.00,
'product2': 3000.50
},
datetime.datetime.strptime('2016-10-09', '%Y-%m-%d'): {
'product1': 2700.00,
'product2': 2800.50,
'product3': 3600.00
},
datetime.datetime.strptime('2016-10-15', '%Y-%m-%d'): {
'product1': 2500.00,
'product2': 2700.00,
'product4': 666.00
}
}
我使用以下方法对字典进行序列化和反序列化:
def get_current_datafile():
with open(name='datafile.raw', mode='rb') as input_handle:
input_dict = pickle.loads(input_handle.read())
return input_dict
def write_datafile(new_dict):
with open(name='datafile.raw', mode='wb') as output_handle:
pickle.dump(new_dict, output_handle)
当我在一个环境中使用序列化文件时,它工作正常。但是当我尝试在不同的机器上反序列化同一个文件时,Python环境的设置完全相同,不起作用,给我一个追溯声称我没有安装datetime模块,这当然不是真的
Traceback (most recent call last):
File "scraper.py", line 92, in <module>
Scraper().main()
File "scraper.py", line 32, in main
input_dict = self.get_current_datafile()
File "scraper.py", line 82, in get_current_datafile
input_dict = pickle.loads(input_handle.read())
File "Python\lib\pickle.py", line 1388, in loads
return Unpickler(file).load()
File "Python\lib\pickle.py", line 864, in load
dispatch[key](self)
File "Python\lib\pickle.py", line 1096, in load_global
klass = self.find_class(module, name)
File "Python\lib\pickle.py", line 1130, in find_class
__import__(module)
ImportError: No module named datetime
我所知道的环境之间的区别仅在于Windows版本 - 一台机器正在运行:
Python 2.7.12
Pickle r. 72223
Windows 7 x64
另一个正在运行:
Python 2.7.12
Pickle r. 72223
Windows 10 x64
问题是:我应该如何配置我的环境,以便我可以在它们之间一致地序列化和反序列化文件?
答案 0 :(得分:1)
我刚遇到了这个问题。问题是pickle文件中的行结尾。 Windows下的Python 2.7.13只使用换行符来保存它们。
在第二台机器上,我正在从GIT中检索它们,而Tortoise GIT for windows则自动将行结尾从换行符转换为回车符/换行符。
因此,请确保您的行结尾不会在计算机之间进行转换。只要我转换回换行符,导入错误就会消失。