import pickle
ListNames = [["Name1","City1","Email1"],["Name2","City2","Number2"]]
ListNumbers = [1,2,3,4,5,6,7,8]
with open ("TestPickle.pickle","wb") as fileSaver:
pickle.dump(ListNames,fileSaver)
pickle.dump(ListNumbers,fileSaver)
with open ("TestPickle.pickle","rb") as fileOpener:
print(pickle.load(fileOpener))
输出结果为:
[['Name1', 'City1', 'Email1'], ['Name2', 'City2', 'Number2']]
如何让pickle加载ListNumbers
我知道我可以再次打印pickle.load但是如果我的pickle文件中有一些未知数量的项目有多个数据类型(例如:列表,元组,字典,字符串......)
谢谢
答案 0 :(得分:0)
我知道我可以再次打印pickle.load但是如果我的pickle文件中有一些未知数量的项目有多个数据类型(例如:列表,元组,字典,字符串......)
有几种解决方法:
pickle.load()
。答案 1 :(得分:0)
以前没有尝试过像以前那样在pickle文件中添加多个东西,但很高兴看到它是可能的。看看this回答。如果你在没有with
的情况下调用它两次,它应该可以解决所有问题:
f = open("TestPickle.pickle", "r")
ListNames = pickle.load(f)
ListNumbers = pickle.load(f)
f.close()
或者您可以像这样保留with
:
with open("TestPickle.pickle", "rb") as f:
ListNames,ListNumbers = pickle.load(f)
然后,
如果我的pickle文件中包含多个数据类型
的项目数量未知,该怎么办?
将某些东西倒入泡菜文件中是否真的是一个明智的想法,所以你不知道它里面有什么东西?
答案 2 :(得分:0)
我不确定这是否是正确的做法。
import pickle
ListNames = [["Name1","City1","Email1"],["Name2","City2","Number2"]]
ListNumbers = [1,2,3,4,5,6,7,8]
with open ("TestPickle.pickle","wb") as fileSaver:
pickle.dump(ListNames,fileSaver)
pickle.dump(ListNumbers,fileSaver)
obj = []
with open("TestPickle.pickle","rb") as fileOpener:
while True:
try:
obj.append(pickle.load(fileOpener))
except EOFError:
break
print obj
<强>输出:强>
[[['Name1', 'City1', 'Email1'], ['Name2', 'City2', 'Number2']], [1, 2, 3, 4, 5, 6, 7, 8]]