python全栈闯关--20-序列化

序列化简介

干什么?

序列化:数据机构转→字符串
反序列化:字符串→数据结构

用途:

数据存储
网络上传输

使用模块:

  • josn
  • pickle
  • shelve

json:

  可以转换数字、字符串、列表、字典、元祖
  通用的序列化格式
  只有很少的一部分数据类型能够通过json转换成字符串

pickle:

  所有python中的数据类型,都可以转换成字符串
  pickle序列化的内容只有python能理解
  反序列化依赖python代码

shelve:

  序列化句柄
  使用句柄操作,非常方便

json

使用dumps和loads在内存中进行转换:

d = dict([(1,'a'),(2,'b'),(3,'d')])
print(type(d), d)
# <class 'dict'> {1: 'a', 2: 'b', 3: 'd'}
s_d = json.dumps(d)
print(type(s_d), s_d)
# <class 'str'> {"1": "a", "2": "b", "3": "d"}  字符串类型中,字符使用双引号
dic_d = json.loads(s_d)
print(type(dic_d), dic_d)
# <class 'dict'> {'1': 'a', '2': 'b', '3': 'd'}  键值变成了字符,不是开始的整数

使用dump和load在写入文件和从文件中读取:

f = open('fff',mode='w',encoding='utf-8')
json.dump(d,f)
f.close()

f = open('fff',mode='r')
fd= json.load(f)
print("%s fd:%s)" %(type(fd),fd))
f.close()

d = {1:'这个',2:'哪个'}
f = open('fff',mode='w',encoding='utf-8')
json.dump(d,f,ensure_ascii=True)
# 含有中文,写入文件的内容是乱码
# true是写入文件的是字符编码
# false吸入文件的内容是可读的
f.close()

f = open('fff',mode='r',encoding='utf-8')
#  读取时,不加字符编码,系统使用默认的字符加载二进制,可能会报错
fd= json.load(f)
print("%s fd:%s)" %(type(fd),fd))
f.close()

json不能多次写,但是使用文件操作和dumps、loads可以变通实现

# json只能一次性写入,不能一次读取多行
# 要写入存入多行,就只能使用dumps往文件写入多行,逐行读取后,使用loads转换
l = [{'k1':'11'},{'k2':'22'},{'k3':'33'}]
with open('多次读写.txt',mode='w', encoding='utf-8') as f:
    for d in l:
        str_dic = json.dumps(d)
        f.write(str_dic+'\n')

d_list = []
with open('多次读写.txt',mode='r',encoding='utf-8') as f:
    for l in f:
        dic = json.loads(l.strip())
        d_list.append(dic)

print(d_list)

pikcle

操作跟json一致,但是pickle支持多次读写,和所有的数据结构

import pickle
import time
d = dict([(1,'a'),(2,'b'),(3,'d')])
dic_str = pickle.dumps(d)
print(type(dic_str), dic_str)
# <class 'bytes'> b'\x80\x03}q\x00(K\x01X\x01\x00\x00\x00aq\x01K\x02X\x01\x00\x00\x00bq\x02K\x03X\x01\x00\x00\x00dq\x03u.'
d2 = pickle.loads(dic_str)
print(d2)

#pickle 转换后的结果未二进制的,因此读出和写入都必须使用rb模式
# pickle可以对此写入和读出
with open('pickle_file',mode='wb') as f:
    pickle.dump(d, f)
    pickle.dump(time.localtime(), f)
# 存储后,文件内容是乱码

with open('pickle_file',mode='rb') as f:
    d1 = pickle.load(f)
    d2 = pickle.load(f)
print(type(d1), d1)
print(type(d2), d2)

shelve

直接通过文件句柄进行操作

print('shelve begin:'.center(50,'-'))
import shelve
f = shelve.open('shelve_file') # 直接对文件句柄进行操作,就可以存入数据
f['time'] = time.localtime()
f['name'] = ['juse', 'tom', 'lisan']
f.close()

with shelve.open('shelve_file',writeback=True) as s:
    s1 = s['time'] # key 值不存在报错
    s2 = s['name']
    s['name'][1] = 'alter edit123' # 如果不加writeback=True,对列表的修改,将不会返回给文件
print(type(s1), s1)
print(type(s2), s2)

猜你喜欢

转载自www.cnblogs.com/zxw-xxcsl/p/12660915.html