python中的序列化

  • 序列化

    • 转向一个字符串数据类型
    • 从数据类型转向字符串的过程叫序列化
  • 反序列化

    • 从字符串到数据类型的过程叫反序列化
  • 序列

    • 字符串
  • 在什么情况下用字符串

    • 写文件(数据存储)
    • 网络上进行传输
  • json

    • 通用的序列化格式
      • 不仅python用,java等其他语言也用
    • 只有很少的一部分数据类型能够通过json转化成字符串
    • dumps 序列化方法
    • loads 反序列化方法
    • 数字 字符串 列表 字典
    • 元组的序列化
      • 序列化后成为了列表
      • 反序列化后还是列表
    • 集合不能序列化
    • dump load
      • 和文件相关
python 复制代码
import json
dic = {"k1": 'v1'}print(type(dic), dic)    # <class 'dict'> {'k1': 'v1'}
str_d = json.dumps(dic)
print(type(str_d), str_d)  # <class 'str'> {"k1": "v1"}


dic_d = json.loads(str_d)
print(type(dic_d), dic_d)  # <class 'dict'> {'k1': 'v1'}
python 复制代码
import json
dic = {1:"a", 2:'b'}
f = open("test", 'w', encoding="utf-8")
json.dump(dic, f)
f.close()
python 复制代码
import json
f = open("test", 'r')
dic = json.load(f)
f.close()
print(type(dic), dic) # <class 'dict'> {'1': 'a', '2': 'b'}
python 复制代码
import json
dic = {1:"中国", 2:'b'}
f = open("test", 'w', encoding="utf-8")
json.dump(dic, f, ensure_ascii=False)
f.close()

# import json
f = open("test", 'r', encoding="utf-8")
dic = json.load(f)
f.close()
print(type(dic), dic) # <class 'dict'> {'1': '中国', '2': 'b'}
python 复制代码
l = [{'k':"123"}, {'k':"dfd"}, {'k':"123df"}]
import json
f = open("file", 'w')
for dic in l:
    str_dic = json.dumps(dic)
    f.write(str_dic+"\n")
f.close()
python 复制代码
f = open("file")
l = []
import json
for line in f:
    dic = json.loads(line.strip())
    l.append(dic)
f.close()
print(l)
  • pickle
    • 所有的python中的数据类型都可以转化成字符串形式
    • pickle序列化的内容只有python能理解
    • 且部分反序列化依赖代码
    • 可以分步dump和load
    • 文件读写需要加 'b'
python 复制代码
import pickle
dic = {"k1":"v1", "k2":"v2", "k3":"v3"}
str_dic = pickle.dumps(dic)
print(str_dic) # b'\x80\x03}q\x00(X\x02\x00\x00\x00k1q\x01X\x02\x00\x00\x00v1q\x02X\x02\x00\x00\x00k2q\x03X\x02\x00\x00\x00v2q\x04X\x02\x00\x00\x00k3q\x05X\x02\x00\x00\x00v3q\x06u.'

dic2 = pickle.loads(str_dic)
print(dic2) # {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
python 复制代码
import time
import pickle
struct_time = time.localtime(10000000)
print(struct_time) # time.struct_time(tm_year=1970, tm_mon=4, tm_mday=27, tm_hour=1, tm_min=46, tm_sec=40, tm_wday=0, tm_yday=117, tm_isdst=0)
f = open("pickle_file", 'wb')
pickle.dump(struct_time, f)
f.close()
python 复制代码
import pickle
f = open("pickle_file", 'rb')
struct_time2 = pickle.load(f)
print(type(struct_time2)) # <class 'time.struct_time'>
print(struct_time2.tm_year) # 1970
python 复制代码
import time
import pickle
struct_time1 = time.localtime(10000000000)
struct_time2 = time.localtime(20000000000)
print(struct_time1)
print(struct_time2)
f = open("pickle_file", 'wb')
pickle.dump(struct_time1, f)
pickle.dump(struct_time2, f)
f.close()

# import time
import pickle
f = open("pickle_file", 'rb')
struct_time1 = pickle.load(f)
struct_time2 = pickle.load(f)
print(struct_time1.tm_year) # 2286
print(struct_time2.tm_year) # 2603
f.close()
  • shelve
    • 序列化句柄

    • 使用句柄直接操作,非常方便

      import shelve

      f2 = shelve.open("shelve_file", writeback=True)

      print(f2["key"])

      f2["key"]["new_value"] = "this was not here before"

      f2.close()

      f2 = shelve.open("shelve_file")
      print(f2["key"]) # {'int': 10, 'float': 9.5, 'str': 'abc', 'new_value': 'this was not here before'}
      f2.close()

相关推荐
代码山河2 小时前
Python就业方向全解析:后端、爬虫、数据分析、AI你选哪个?
python·学习·架构·教程·面向对象·项目
在世修行2 小时前
智学文枢:题目流水线
python·多线程·状态机·pyside
HideF2 小时前
Linux
linux·服务器·网络
梯度下降者3 小时前
零基础入门Python 爬虫
爬虫·python·数据分析·入门指南·webcrawler
小徐不徐说4 小时前
C++ 接口与插件设计:从工厂注册到 Qt 动态插件
数据库·c++·qt·系统架构·程序设计
“AI国潮设计-小江”4 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
Ruiery4 小时前
Linux 6.6内核内存管理深度解析(十三):slab/slub 分配器
linux·运维·服务器
论文复现现场5 小时前
WRF、FEA 能用 L40S 加速吗?求解器检查、断点恢复与长期运行
java·数据库·算法·wrf·有限元分析·gpu计算·断点续算
乌恩大侠5 小时前
从 AI-RAN 到 AI Agent:基于 NVIDIA Nemotron 构建 5G/6G 智能网络故障诊断系统
服务器·人工智能·5g·o-ru·ai-ran·电信大模型
benchmark_cc5 小时前
用 Python 拉 A 股全市场实时快照:Notebook 请求、结果校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash