Python:pickle模块

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 ('按任意键退出:')

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值