Skip to main content
 首页 » 编程设计

python之存储 'object'

2025年05月04日17虾米哥

PyTables 是否支持存储 Python 对象? 像这样:

dtype = np.dtype([('Name', '|S2'), ('objValue', object)]) 
data = np.zeros(3, dtype) 
file.createArray(box3,'complicated',data) 

我当然会在尝试这样做时出错... 如何正确存储对象数组?可能吗? 谢谢

请您参考如下方法:

您可以使用 Pytables 保存通用 Python 对象:

>>> dtype = np.dtype([('Name', '|S2'), ('objValue', object)]) 
>>> data = np.zeros(3, dtype) 
>>> file = tables.openFile('/tmp/test.h5', 'w') 
>>> myobjects = file.createVLArray(file.root, 'myobjects', tables.ObjectAtom()) 
>>> myobjects.append(data) 
>>> myobjects[0] 
array([('', 0), ('', 0), ('', 0)],  
      dtype=[('Name', '|S2'), ('objValue', '|O8')]) 

但是,这将在幕后使用 pickle(实际上是 cPickle),因此您将无法从其他语言访问这些对象(pickle 是一种仅 Python 本身支持的序列化格式)。