如何使用 pickle 将两个列表写入 dat 文件?
How do I write two lists to a dat file using pickle?
我很确定我的格式有误,而且我实际上并没有向该文件写入任何内容。我正在尝试将 aList
和 bList
写入 aFile
。
aList = ['useless', 'info']
bList = [1000,5000]
with open('aFile.dat', 'w') as f:
pickle.dump('aFile.dat', f)
您可以使用键 aList 和 bList 创建字典并将其保存到 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"))
我很确定我的格式有误,而且我实际上并没有向该文件写入任何内容。我正在尝试将 aList
和 bList
写入 aFile
。
aList = ['useless', 'info']
bList = [1000,5000]
with open('aFile.dat', 'w') as f:
pickle.dump('aFile.dat', f)
您可以使用键 aList 和 bList 创建字典并将其保存到 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"))