cPickle 类将数据保存到文件

发布于 2024-09-04 14:07:21 字数 877 浏览 10 评论 0原文

我在 Python 中有一个大类,它是“类似数据库”的类。我想将其保存到文件 - 所有包括数据。

这是输入(显示问题的示例,在脚本数据库中大约有 10000 条记录):

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)`

这就是我得到的文件:

€c__main__
DataBase
q.`

没有数据,只有定义。我怎样才能克服这个问题。也许将我的数据保存为一个类不是一个好主意?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

救星 2024-09-11 14:07:21

您正在腌制“DataBase”,这是一个类定义。您需要实例化 DataBase 类的对象,然后对其进行 pickle。

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

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文