数据的存储与读取:序列化文件pickle()用法
#coding:utf-8
__author__ = 'DBL_fish'
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'}}
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)
fw.close()
#使用load()将数据从文件中序列化读出
fr = open('dateFile.txt','rb')
data_1=pickle.load(fr)
data_2 =pickle.load(fr)
print(data_1)
print(data_2)
fr.close()
#使用dumps()和loads()举例
p = pickle.dumps(dataList)
print(pickle.loads(p))
p = pickle.dumps(dadaDic)
print(pickle.loads(p))
输出:
[[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'}}
[[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
参考链接:
Python数据存储:pickle模块的使用讲解 - coffee_cream的博客 - ****博客 https://blog.****.net/coffee_cream/article/details/51754484
Python3 输入和输出_w3cschool https://www.w3cschool.cn/python3/python3-inputoutput.html