使用Python和pickle来保存对象中的复杂数据

时间:2016-04-26 21:18:03

标签: python list pickle

我正在尝试使用python为一个与python一起工作的程序做一个脚本,我需要将一个对象(里面有自定义类和数组)保存到一个文件中,以便我可以在以后读取它(这样我就不会每次都需要重新制作对象,这需要几个小时)

我在很多论坛上都在阅读,最简单的方法是使用泡菜,但我在某个地方犯了一个错误,我不明白在哪里......

现在,代码将是:

首先我定义这个类:

class Issue_class:
    Title_ID = None
    Publisher_ID = None
    Imprint_ID = None
    Volume = None
    Format = None
    Color = None
    Original = None
    Rating = None
    Issue_Date_Month = None
    Issue_Date_Year = None
    Reprint = None
    Pages = None
    Issue_Title = None
    Number = None
    Number_str = None
    Synopsis = None
    Characters_ID = None
    Groups_ID = None
    Writer_ID = None
    Inker_ID = None
    Colorist_ID = None
    Letterer_ID = None
    CoverArtist_ID = None
    Penciller_ID = None
    Editor_ID = None
    Alternatives_ID = None
    Reprints_ID = None
    Story_ID = None
    Multi = None
    Multistories = None

然后我为这个类定义一个列表/数组:

Issuesdata = []

然后在循环中我填写并将它们附加到列表中:

    Issuedata = Issue_class()

    Issuedata.Color = "unknown"
    Issuedata.Tagline = "none"
    Issuedata.Synopsis = "none"
    Issuedata.Format = "none"
    Issuedata.Publisher_ID = "none"
    Issuedata.Imprint_ID = -1
    Issuedata.Title_ID = -1
    Issuedata.Volume = "none"
    Issuedata.Number = -1
    Issuedata.Number_str = "none"
    Issuedata.Issue_Title = "none"
    Issuedata.Rating = -1
    Issuedata.Pages = -1
    Issuedata.Issue_Date_Year = 0
    Issuedata.Issue_Date_Month = 0
    Issuedata.Original = True
    Issuedata.Reprint = False
    Issuedata.Multi= True
    Issuedata.Letterer_ID = []
    Issuedata.Characters_ID = []
    Issuedata.Story_ID = []
    Issuedata.Groups_ID = []
    Issuedata.Writer_ID = []
    Issuedata.Penciller_ID = []
    Issuedata.Alternatives_ID = []
    Issuedata.Reprints_ID = []
    Issuedata.Inker_ID = []
    Issuedata.Colorist_ID = []
    Issuedata.Editor_ID = []
    Issuedata.CoverArtist_ID = []
    Issuedata.Multistories = []

然后我使用对象内的数据,当它完成后,我将它附加到列表中:

Issuesdata.append(Issuedata)

之后,我在列表中的一个对象中打印一些信息,以确保一切正常:

print Issuesdata[3].Title_ID
print Issuesdata[3].Publisher_ID
print Issuesdata[3].Imprint_ID
print Issuesdata[3].Volume
print Issuesdata[3].Format
etc...

一切正常,打印数据很完美

现在,我尝试将列表保存到文件:

filehandler = open("data.dat","wb")    
pickle.dump(Issuesdata,filehandler)
filehandler.close()

这创建了包含信息的文件......但是当我尝试用以下内容阅读时:

file = open("data.dat",'rb')
Issuesdat = pickle.load(file)
file.close()

Python控制台告诉我"'模块'对象没有属性' Issue_class'"

我想到的第一件事是我正在读错文件...但是我用记事本打开保存的文件,里面装满了错误的数据",就像文件名或代码之外的类的名称...这让我怀疑我在文件中错误地转储数据......

我使用泡菜错了吗?

2 个答案:

答案 0 :(得分:0)

好的,我发现了问题......看来你必须在主模块中定义你的对象的类才能看到它...我在我工作的模块中定义它并调用pickle命令...

答案 1 :(得分:0)

尝试使用pandas库以及以下简单函数:

DataFrame.to_pickle(file-path) pandas Dataframe 保存在pickle中。

pandas.read_pickle(file-path)阅读pickle文件。

您可在此处找到 pandas 参考to_pickle read_pickle