Python序列化,json&pickle&shelve模块

1. 序列化说明

  序列化可将非字符串的数据类型的数据进行存档,如字典、列表甚至是函数等等
  反序列化,将通过序列化保存的文件内容反序列化即可得到数据原本的样子,可直接使用

2. Python中常用的序列化有json和pickle两种,区别如下

  json:只可序列化简单的数据类型,如字典、列表等,其他语言也有json,即json可跨语言进行序列和反序列化
  pickle:python独有的序列化,可序列化一切数据,以二进制的形式保存
  python中json和pickle的用法基本上是一模一样的

  注意:无论是json还是pickle,都只可序列化数据一次

3. json&pickle序列化

# -*- coding:utf-8 -*-
# Author:Wong Du dict = {'name':'wong','age':'23'}
# with open('test','w') as f:
# f.write(dict)
### 报错:TypeError: write() argument must be str, not dict '''
### 把字典用json序列化后写入文件
### json.dumps(obj); json.dump(obj, fp)
### f.write(json.dumps(dict)) == json.dump(dict,f)
'''
import json
with open('test','w') as f:
# f.write(json.dumps(dict))
json.dump(dict,f)
### 成功写入 '''pickle序列化'''
import pickle
def foo():
print("In the foo...")
foo()
with open('test2','wb') as f: #以二进制字节类型写入到文件当中,所以mode = 'wb'
# f.write(pickle.dumps(foo))
pickle.dump(foo,f)
### 写入成功!注意,这里的写入是把foo函数对象写入到文件当中,反序列化后,当代码里没有foo函数对象,则会报错 list = [1,2,3,4,'name']
with open('test3','wb') as f:
# f.write(pickle.dumps(list))
pickle.dump(list,f)

4. json&pickle反序列化

# -*- coding:utf-8 -*-
# Author:Wong Du # with open('test','r') as f:
# print(f.read())
# f.read()['name']
### 报错:TypeError: string indices must be integers '''
### json反序列化读取文件内容,可直接获取到字典,进行元素调用
### json.loads(str); line = json.load(fp)
### line = json.loads(f.read()) == line = json.load(f)
'''
import json
with open('test','r') as f:
# line = json.loads(f.read())
line = json.load(f)
print(type(line))
print(line['age'])
### 成功调用
'''
输出:
<class 'dict'>
23
''' import pickle
def foo():
print("In the foo2...")
with open('test2','rb') as f: #以二进制字节类型读取文件内容,所以mode = 'rb'
# line = pickle.loads(f.read())
line = pickle.load(f)
line() with open('test3','rb') as f:
# line = pickle.loads(f.read())
line = pickle.load(f)
print(type(line))
print(line[4])

5. shelve模块序列化的使用

  shelve模块可序列化数据多次

# -*- coding:utf-8 -*-
# Author:Wong Du '''
shelve模块可多次序列化并能简单的找到其中对应的数据
即shelve模块以字典的形式进行k和v的关键字对应数据序列化
''' import shelve dict = {'name':'wong','age':'23','sox':'man'}
list = ['you','happy','jiu','OK']
f1 = open('高并发socket_client.py') # 序列化数据
with shelve.open('shelve.txt') as f:
f['dict'] = dict
f['list'] = list
f['file'] = f1.read() # 调用shelve序列化的数据
with shelve.open('shelve.txt') as f:
print(f['dict'])
print(f['dict']['name'])
print(f['file'])

上一篇:Python json & pickle & shelve模块


下一篇:json & pickle & shelve 模块