python的pickle模块实现了基本的数据序列和反序列化。
通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。
通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
pickle 模块几乎可以把所有的 Python 的对象都转化为二进制的形式存放,这个过程称为 pickling,从二进制形式转换回对象的过程称为 unpickling。
基本接口:
pickle.dump(obj, file, [,protocol])
有了 pickle 这个对象, 就能对 file 以读取的形式打开:
x = pickle.load(file)
从 file 中读取一个字符串,并将它重构为原来的 python 对象。
file: 类文件对象,有 read() 和 readline() 接口。
例1:
>>> import pickle
>>>
>>> # 存储
>>> my_list = [123, 3.14, '姓名', ['A', 'B']]
>>> pickle_file = open('D:\\Python\\test\\my_list.pickle', 'wb') # 后缀名随意。一定要用二进制模式wb
>>> pickle.dump(my_list, pickle_file)
>>> pickle_file.close()
>>>
>>> # 读取
>>> pickle_file = open('D:\\Python\\test\\my_list.pickle', 'rb') # rb:二进制格式打开,只读
>>> my_list2 = pickle.load(pickle_file)
>>> print(my_list2)
[123, 3.14, '姓名', ['A', 'B']]
例2:存储两条数据,逐一读取
import pickle
# 使用pickle模块将数据对象保存到文件
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
output = open('D:\\Python\\test\\data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump(data1, output)
# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)
output.close()
# IDLE读取
>>> import pickle
>>> pickle_file = open('D:\\Python\\test\\data.pkl', 'rb')
>>> a = pickle.load(pickle_file)
>>> a
{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
>>>
>>> b = pickle.load(pickle_file)
>>> b
[1, 2, 3, [...]]
>>>
>>> c = pickle.load(pickle_file) # 超出数据条数,报错
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
c = pickle.load(pickle_file)
EOFError: Ran out of input
# .py读取
import pprint, pickle
#使用pickle模块从文件中重构python对象
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()
例3:
将以下查询天气预报的代码中城市字典做成泡菜单独存储。(城市字典已简化、代码接口已失效。仅做泡菜应用演示)
# 原始代码
import urllib.request
import json
#建立城市字典
city = {
'北京': '101010100',
'台中': '101340401'
}
password=input('请输入城市:')
name1=city[password]
File1 =urllib.request.urlopen('http://m.weather.com.cn/data/'+name1+'.html')#打开url
weatherHTML= File1.read().decode('utf-8')#读入打开的url
weatherJSON = json.JSONDecoder().decode(weatherHTML)#创建json
weatherInfo = weatherJSON['weatherinfo']
#打印信息
print ( '城市:', weatherInfo['city'])
print ('时间:', weatherInfo['date_y'])
print ( '24小时天气:')
print ('温度:', weatherInfo['temp1'])
print ('天气:', weatherInfo['weather1'])
print ('风速:', weatherInfo['wind1'])
print ('紫外线:', weatherInfo['index_uv'])
print ('穿衣指数:', weatherInfo['index_d'])
print ('48小时天气:')
print ('温度:', weatherInfo['temp2'])
print ('天气:', weatherInfo['weather2'])
print ('风速:', weatherInfo['wind2'])
print ('紫外线:', weatherInfo['index48_uv'])
print ('穿衣指数:', weatherInfo['index48_d'])
print ('72小时天气:')
print ('温度:', weatherInfo['temp3'])
print ('天气:', weatherInfo['weather3'])
print ('风速:', weatherInfo['wind3'])
input ('按任意键退出:')
开始泡菜:
# 泡菜进坛~~~
city = {
'北京': '101010100',
'台中': '101340401'
}
import pickle
pickle_file = open('city_data.pkl', 'wb')
pickle.dump(city, pickle_file)
pickle_file.close()
import urllib.request
import json
import pickle #开启泡菜
pickle_file = open('city_data.pkl', 'rb')
city = pickle.load(pickle_file)
password=input('请输入城市:')
name1=city[password]
File1 =urllib.request.urlopen('http://m.weather.com.cn/data/'+name1+'.html')#打开url
weatherHTML= File1.read().decode('utf-8')#读入打开的url
weatherJSON = json.JSONDecoder().decode(weatherHTML)#创建json
weatherInfo = weatherJSON['weatherinfo']
#打印信息
print ( '城市:', weatherInfo['city'])
print ('时间:', weatherInfo['date_y'])
print ( '24小时天气:')
print ('温度:', weatherInfo['temp1'])
print ('天气:', weatherInfo['weather1'])
print ('风速:', weatherInfo['wind1'])
print ('紫外线:', weatherInfo['index_uv'])
print ('穿衣指数:', weatherInfo['index_d'])
print ('48小时天气:')
print ('温度:', weatherInfo['temp2'])
print ('天气:', weatherInfo['weather2'])
print ('风速:', weatherInfo['wind2'])
print ('紫外线:', weatherInfo['index48_uv'])
print ('穿衣指数:', weatherInfo['index48_d'])
print ('72小时天气:')
print ('温度:', weatherInfo['temp3'])
print ('天气:', weatherInfo['weather3'])
print ('风速:', weatherInfo['wind3'])
input ('按任意键退出:')