cPickle class with data save to file

谁说胖子不能爱 提交于 2020-01-16 18:17:16

问题


I've big class in Python it's "DataBase-like" class. I want to save it to file - all including data.

This is input(example to show the issue, in script database is like 10000 records):

import cPickle
# DataBase-like class
class DataBase:
    class Arrays: pass
    class Zones: pass
    class Nodes: 
        class CR: pass    
    class Links: 
        class CR: pass
    class Turns:
        class CR: pass    
    class OrigConnectors: pass
    class DestConnectors: pass    
    class Paths: pass
    pass
# some basic input into database
DataBase.Arrays.Data=[]
for i in range(1000):
    DataBase.Arrays.Data.append([i+4]) 

print DataBase.Arrays.Data[56]

# and now I want to save it to file

import cPickle    

filename='D:/results/file.lft'
file=open(filename,'w')
cPickle.dump(DataBase, file, protocol=2)`

And that's the file I get:

€c__main__
DataBase
q.`

There's no data, just definition. How can I overcome that. Maybe saving my data as a class is not a good idea?


回答1:


You are pickling "DataBase" which is a class definition. You need to instantiate an object of class DataBase then pickle that.

objDataBase = DataBase()
objDataBase.Arrays.Data = etc....

filename='D:/results/file.lft'
file=open(filename,'w')
cPickle.dump(objDataBase, file, protocol=2)
file.close()


来源:https://stackoverflow.com/questions/2991557/cpickle-class-with-data-save-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!