Python-pickle/json基础用法

发布时间 2023-07-03 14:44:25作者: 许个未来—
"""
-*- coding: utf-8 -*-
@FileName: json_pickle.py
@Software: PyCharm
@Time    : 2023/7/3 14:36
@Author  : Panda
"""


# 1.pickle 模块:序列化模块
import pickle

"""
序列化:把不能直接存储在文件中的数据变得可存储
反序列化:把存在文件中的数据拿出来恢复成原来的数据类型
"""

lst = [1, 2, 3]
# dumps()把任意对象序列化成bytes
res = pickle.dumps(lst)
print(res, type(res))

# 函数可以序列化吗?可以
def func():
    print("ok")
res1 = pickle.dumps(func())
print(res, type(res))

# 迭代器可以序列化吗?可以
it = iter(range(10))
res2 = pickle.dumps(it)
print(res, type(res))

# loads() 把任意bytes反序列化为原来的数据
res3 = pickle.loads(res)
print(res, type(res))

# dump():把对象序列化写入到file_like Object(即文件对象)
res - pickle.dump(lst)
with open("study.txt", mode="wb") as fp :
    pickle.dump(res, fp)

# load(): 把file_like Object中的内容拿出来,反序列化成原来的数据
with open ("study.txt", mode="rb") as fp :
    res4 = pickle.load(fp)
print(res4)


# 2. json 模块 : 序列化/反序列化模块
import json

"""
json格式的数据,所有的编程语言都能识别,本身是字符串
类型有格式要求:int float bool str list tuple dict None

json: 主要应用于传输数据, 序列化成字符串
pickle: 主要应用于存储数据, 序列化成二进制字节流
"""
dic = {"name": "opp", "sex": "kkl", "family": ['baby', "me"]}
res = json.dumps(dic, ensure_ascii=False, sort_keys=True)
print(res, type(res))

dci = json.loads(res)
print(res, type(res))


# json > dump/load

with open("ss.pkl", mode="w", encoding="utf-8") as fp:
    json.dump(dic, fp, ensure_ascii=False)

with open("ss.pkl", mode="w", encoding="utf-8") as fp:
    json.load(fp)
print(dic, type(dic))

# json和pickle 的区别
# json 是连续dumps数据,但是不能连续load数据,是一次性获取所有内容进行反序列化
dic1 = {"a": "1", "b": "2"}
dic2 = {"c": "3", "d": "4"}
with open("sss.txt", mode="w", encoding="utf-8") as fp:
    json.dump(dic1, fp)
    fp.write("\n")
    json.load(dic2, fp)
    fp.write("\n")

with open("sss.pkl", mode="r", encoding="utf-8") as dp:
    dic = json.load(fp)

# json和pickle两个模块的区别:
# 1. json序列化之后的数据类型是str,所有编程语言都识别
    # 但是仅限于int float bool str list tuple dict None
    # json不能连续load,只能一次性拿出所有数据
# 2.pickle序列化之后的数据类型是bytes,用于数据存储
    # 所有的数据都可以转化,但是仅限于python之间的存储传输
    # pickle可以连续load,多套数据放在同一个文件夹中