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()

相关推荐
花酒锄作田8 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪12 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽12 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战13 小时前
Pydantic配置管理最佳实践(一)
python
jiayou6418 小时前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
阿尔的代码屋18 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python