# 仅仅支持列表、字典、字符串、数字
import json
# 几乎支持python中所有的数字类型
import pickle
#
import shelve
# dumps loads
dic = {'aaa': 'bbb', 'ccc': 'ddd'}
str_dic = json.dumps(dic)
print(dic)
# 从dic转换到str
print(str_dic, type(str_dic)) # str
# 写入文件中
with open('json_dump', 'w') as f:
f.write(str_dic)
# 从str转换到dic
ret = json.loads(str_dic) # dic
print(ret, type(ret))
# dump load
# 写入文件中
with open('json_dump1', 'w') as f:
json.dump(dic, f)
# 读取文件
with open('json_dump1', 'r') as f:
read = json.load(f)
print(read, type(read))
dic = {1: (12, 3, 4), ('a', 'b'): 4}
pic_dic = pickle.dumps(dic)
print(type(pic_dic)) # bytes
new_dic = pickle.loads(pic_dic)
print(new_dic)
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
alex = Student('male', 23)
print(pickle.dumps(alex)) # byte
with open('pickle_demo', 'wb') as f:
pickle.dump(alex, f)
with open('pickle_demo', 'rb') as f:
read_pickle = pickle.load(f)
print(read_pickle.name)
f = shelve.open('shelve_demo')
f['key'] = {'k1': (1, 2, 3), 'k2': 'v2'}
f.close()
f = shelve.open('shelve_demo')
content = f['key']
f.close()
print(content)
Python:序列化
最新推荐文章于 2023-02-17 14:40:49 发布