#coding:utf-8
__author__ = 'DBL_fish'
import pickle
import pickle
dataList = [[8,8,'hei'],
[6,6,'ha'],
[1,0,'he']]
dadaDic = {0:[1,6,8,3],
1:('c','d'),
2:{'c':'heng','d':'ha'}}
dataset = {1,2,2,2,3}
a =15
print(dataset,type(dataset))
print(dataList,type(dataList))
print(dadaDic,type(dadaDic))
#使用dump()将数据序列化到文件中 pickle(腌制)
fw = open('dateFile.txt','wb')
#Pickle the list using the highest protocol available
pickle.dump(dataList,fw,-1)
#Pickle the dictionary using protocol 0
pickle.dump(dadaDic,fw)
pickle.dump(dataset,fw)
pickle.dump(a,fw)
fw.close()
#使用load()将数据从文件中序列化读出
fr = open('dateFile.txt','rb')
data_1=pickle.load(fr)
data_2 =pickle.load(fr)
data_3 = pickle.load(fr)
data_4 = pickle.load(fr)
print(data_1)
print(data_2)
print(data_3)
print(data_4)
fr.close()
#使用dumps()和loads()举例
p = pickle.dumps(dataList)
print(pickle.loads(p))
p = pickle.dumps(dadaDic)
print(pickle.loads(p))
输出:
{1, 2, 3} <class 'set'>
[[8, 8, 'hei'], [6, 6, 'ha'], [1, 0, 'he']] <class 'list'>
{0: [1, 6, 8, 3], 1: ('c', 'd'), 2: {'c': 'heng', 'd': 'ha'}} <class 'dict'>
[[8, 8, 'hei'], [6, 6, 'ha'], [1, 0, 'he']]
{0: [1, 6, 8, 3], 1: ('c', 'd'), 2: {'c': 'heng', 'd': 'ha'}}
{1, 2, 3}
15
[[8, 8, 'hei'], [6, 6, 'ha'], [1, 0, 'he']]
{0: [1, 6, 8, 3], 1: ('c', 'd'), 2: {'c': 'heng', 'd': 'ha'}}
Process finished with exit code 0
给我的教训是:注意dumps与dump load与loads 吃一堑长一智
参考链接:
Python数据存储:pickle模块的使用讲解 - coffee_cream的博客 - CSDN博客 https://blog.csdn.net/coffee_cream/article/details/51754484
Python3 输入和输出_w3cschool https://www.w3cschool.cn/python3/python3-inputoutput.html
263

被折叠的 条评论
为什么被折叠?



