python 序列化操作模块pickle&json
dumps 将对象序列化成bytes对象;
dump 对象序列化到文件对象,就是存入文件;
loads 从bytes对象反序列化;
load 对象反序列化,从文件读取数据;
# 1、序列化,数据到文件,就dump;
# 2、反序列化,文件到数据,就load;
# 3、根据字符串转换就加s;
# 4、从文件直接转就不加s;
# pickle模块是python专用的持久化模块,可以持久化包括自定义类在内的各种数据;只能在python程序之间进行数据交换;
# 注意:在使用dump()序列化时候,打开文件必须要以wb模式,使用load()反序列化,打开文件必须以rb模式;
# JSON:JavaScript Object Notation,JS对象标记,是一种轻量级的数据交换格式;
# Json是跨平台语言,所以只能对python的基本数据类型进行操作,无法识别python的类;
import os, sys, pickle, json
desk_path = os.path.join(os.path.expanduser("~"), "Desktop")
file_path = desk_path + "/wyh_files/wyh_test_pickle_json.pkl"
data = {"name": '张三', "age": 18}
data_dumps = pickle.dumps(data)
print(data_dumps)
data_loads = pickle.loads(data_dumps)
print(data_loads)
with open(file_path, "wb", ) as f:
pickle.dump(data, f)
with open(file_path, "rb") as f:
contents = pickle.load(f)
print(contents)
file_path = desk_path + "/wyh_files/wyh_test_pickle_json.json"
data_dumps = json.dumps(data)
print(data_dumps)
data_loads = json.loads(data_dumps)
print(data_loads)
with open(file_path, "w") as f:
json.dump(data, f)
with open(file_path, "r") as f:
contents = json.load(f)
print(contents)