如何使用pickle将两个列表写入dat文件?

时间:2015-03-10 02:48:16

标签: list python-2.7 pickle

我非常确定我的格式错误,并且我实际上并没有在此文件中写入任何内容。我试图将aListbList写入aFile

aList = ['useless', 'info']
bList = [1000,5000]

with open('aFile.dat', 'w') as f:
    pickle.dump('aFile.dat', f)

1 个答案:

答案 0 :(得分:0)

您可以使用键aList和bList创建一个dict,并将其保存到aFile,如下所示:

import pickle

aList = ['useless', 'info']
bList = [1000,5000]

aFile=open('aFile.dat', 'w')
aFile.write(pickle.dumps({"aList":aList,"bList":bList}))
aFile.close()

如果您希望附加信息,可以做一些更详细的说明:

import pickle


def extract_dict(filename):
    try:
        oldInfoFile=open(filename, 'r')
    except:
        print "File could not be opened"
        return {}
    oldInfo=oldInfoFile.read()
    oldInfoFile.close()
    try:
        oldDict=pickle.loads(oldInfo)
    except AttributeError:
        print "Non valid Pickle format"
        return {}
    return oldDict

def append_dict(filename,more_info_dict):
    myDict=extract_dict(filename)
    myDict.update(more_info_dict)
    aFile=open(filename, 'w')
    aFile.write(pickle.dumps(myDict))
    aFile.close()


#Testing what we have in aFile.dat
print(extract_dict("aFile.dat"))

aList = ['useless', 'info']
bList = [1000,5000]
first_info={"aList":aList,"bList":bList}

#Adding data to aFile.dat
append_dict("aFile.dat",first_info)

#Verifying data was written to aFile.dat
print(extract_dict("aFile.dat"))

second_info={"aList2":aList,"bList2":bList}

#Writting more data    
append_dict("aFile.dat",second_info)

#Verifying new data was written to aFile.dat
print(extract_dict("aFile.dat"))