今日主要内容
序列化 把对象打散成二进制字节 bytes
1. pickle 把一个对象转化成bytes写入到文件( pickle序列化的内容是⼆进制的内容(bytes) 不是给⼈看的.)
pickle.dumps() 把对象转换成bytes
pickle.loads() 把bytes转化成对象
pickle.dump() 把对象转换成bytes. 写入到文件
pickle.load() 把文件中的bytes读取. 转化成对象
例 import pickle
class Fruit:
def __init__(self,name,color):
self.name = name
self.color = color
def eat(self):
return "haochi"
p1 = Fruit("apple1","red1") # 赋值
p2 = Fruit("apple2","red4")
p3 = Fruit("apple3","red2")
p4 = Fruit("apple4","red6")
lst = [p1,p2,p3,p4] # 装进一个列表
pickle.dump(lst,open("fruit_info","wb")) # 把对象转换成bytes. 写入到文件
lst = pickle.load(open("fruit_info","rb")) # 把文件中的bytes读取. 转化成对象
for i in lst: # 遍历这个对象
print(i.name) # 打印这个对象的 名字或者颜色
2. shelve 小型数据库, redis, mongodb, dict
当成字典来用
writeback=True
例 import shelve
d = shelve.open("sylar") # 文件类型的字典
d['wf'] = "汪峰"
d.close()
d = shelve.open("sylar")
print(d['wf'])
d.close()
d = shelve.open("sylar") # 文件类型的字典
d['wf'] = {"name":"汪峰", "age": 18, "wife":{"name":"章子怡", "hobby":"拍电影"}}
d.close()
d = shelve.open("sylar", writeback=True) # 文件类型的字典 wirteback把修改的内容自动的回写到文件中
d['wf']['wife']['hobby'] = "当导师" # 改
d.close()
d = shelve.open("sylar") # 文件类型的字典
print(d['wf'])
d.close()
3. json 以前用xml 先在用json (ensure_ascii = False 可以处理中文)
json.dumps() 把字典转换成json字符串
json.loads() 把json字符串转化成字典
例 字典转字符串
import json
dic = {"a": "⼥王", "b": "萝莉", "c": "⼩清新"}
s = json.dumps(dic) # 把字典转化成json字符串
print(s) # {"a": "u5973u738b", "b": "u841du8389", "c":
"u5c0fu6e05u65b0"}
s = json.dumps(dic, ensure_ascii=False) # 把字典转化成json字符串
print(s) # {"a": "⼥王", "b": "萝莉", "c": "⼩清新"}
例 字符串转字典
s = '{"a": "⼥王", "b": "萝莉", "c": "⼩清新"}'
dic = json.loads(s)
print(type(dic), dic)
例 数据量⼤的话,改⽤dumps和loads. 对每⼀⾏分别进⾏处理.
import json
lst = [{"a": 1}, {"b": 2}, {"c": 3}]
# 写⼊
f = open("test.json", mode="w", encoding="utf-8")
for el in lst:
s = json.dumps(el, ensure_ascii=True) + " "
f.write(s)
f.close()
# 读取
f = open("test.json", mode="r", encoding="utf-8")
for line in f:
dic = json.loads(line.strip())
print(dic)
f.close()
json.dump() 把字典转换成json字符串. 写入到文件
json.load() 把文件中的json字符串读取. 转化成字典
写入到⽂件中
dic = {"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": False, "e": None, "wf":{"name":"半壁江山", "hobby":"皮裤"}}
f = open("sylar.json", mode="w", encoding="utf-8")
json.dump(dic, f, ensure_ascii=False, indent=4) # 4个空格 = 1个tab
从⽂件中读取⼀个json
f = open("sylar.json", mode="r", encoding="utf-8")
d = json.load(f)
print(d)
default = 把对象转化成字典. 需要自己写转换过程
object_hook = 把字典转化成对象. 需要自己写转换过程
4. configparser 处理windows配置文件的 dict