首页 > 编程语言 > python-标准库pickle模块的使用

python-标准库pickle模块的使用

时间:2023-01-13 10:12:51浏览次数:41  
标签:python pickle computer 模块 序列化 open

python-标准库pickle模块

1. python-标准库pickle模块

  • pickle模块实现了对一个Python对象结构的二进制序列化和反序列化。

  • 主要用于将对象持久化到文件存储。

  • pickle模块主要有两个函数:

    • dump() 把对象保存到文件中(序列化),使用load()函数从文件中读取(反序列化)
    • dumps() 把对象保存到内存中,使用loads()函数读取
  • 示例

    • 序列化

      import pickle
      computer = {"主机":5000,"显示器":1000,"鼠标":60,"键盘":150}
      with open("data.pkl", "wb") as f:
      	pickle.dump(computer, f)
      
    • 反序列化

      import pickle
      with open("data.pkl", "rb") as f:
      	print(pickle.load(f))
      

2. 案例

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

import pickle

#  json把一个对象写入到一个文件里面去
computer  = {
    "name":"汪峰",
    "age": 18,
    "hobby":"上头条",
    "wife":{
        "name":'子怡',
        "age":19,
        "hobby":["唱歌","跳舞","演戏"]
    }
}

with open("computer.txt", mode="wb") as f:
	pickle.dump(computer, f)


import pickle
with open("computer.txt", "rb") as f:
	print(pickle.load(f))

标签:python,pickle,computer,模块,序列化,open
From: https://www.cnblogs.com/scajy/p/17048706.html

相关文章