序列化 把对象打散成二进制字节 bytes, 方便对象的存储和传输
python中存在三种序列化方案: pikle , shelve, json
1. pickle 把一个对象转化成bytes写入到文件
pickle.dumps() 把对象转换成bytes
import pickle class Cat: def __init__(self, name, color): self.name = name self.color = color def chi(self): print("%s猫会吃老鼠" % self.name) c = Cat("汪峰","黑色") bs = pickle.dumps(c) # 把一个对象转化成bytes
print(bs)
pickle.loads() 把bytes转化成对象
cc = pickle.loads(bs) # 把⼆进制反序列化成我们的对象
print(cc)
pickle.dump() 把对象转换成bytes. 写入到文件
c1 = Cat("汪峰1","黑色") c2 = Cat("汪峰2","黑色") c3 = Cat("汪峰3","黑色") lst = [c1, c2, c3] f = open("cat.dat", mode="ab") pickle.dump(lst, f) # 把对象写到文件中
pickle.load() 把文件中的bytes读取. 转化成对象
f = open("cat.dat", mode="rb") lst = pickle.load(f) # 从文件中读取第一次
for cc in lst: cc.chi()
记住一点: pikle序列化的内容是二进制内容(bytes), 不是给人看的
2. shelve 小型数据库, 当作dict使用
shelve提供python的持久化操作, 即把数据写在硬盘上
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'] = "当导师" # 不能直接修改, 需要writeback配合
d.close() d = shelve.open("sylar") for k, v in d.items(): print(k, v) # wf {'name': '汪峰', 'age': 18, 'wife': {'name': '章子怡', 'hobby': '当导师'}}
print(type(d)) #<class 'shelve.DbfilenameShelf'>
3. json 以前用xml 先在用json
json.dumps() 把字典转换成json字符串
json.loads() 把json字符串转化成字典
json.dump() 把字典转换成json字符串. 写入到文件
json.load() 把文件中的json字符串读取. 转化成字典
ensure_ascii = False 可以处理中文
mport json # 准备一个字典
dic = {"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": False, "e": None} # python中可以直接把字典或者列表转化成json
s = json.dumps(dic, ensure_ascii=False) # pickle
print(type(s)) # str
print(s) # {"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": false, "e": null} json的打印结果和python有区别
s = '{"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": false, "e": null}' d = json.loads(s) # 把json转化成字典
print(d) # {'a': '小萝莉', 'b': '大萝莉', 'c': '猥琐大叔', 'd': False, 'e': None}
print(type(d)) # dict # 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
f = open("sylar.json", mode="r", encoding="utf-8") d = json.load(f) #
print(d)
default = 把对象转化成字典. 需要自己写转换过程
object_hook = 把字典转化成对象. 需要自己写转换过程
class Person: def __init__(self, firstName, lastName): self.firstName = firstName self.lastName = lastName s = '{"firstName": "尼古拉斯", "lastName": "刘能"}'
def func(dic): return Person(dic['firstName'], dic["lastName"]) p = json.loads(s, object_hook=func) # 通过函数func把字典转换回对象
print(p.firstName, p.lastName) #尼古拉斯 刘能 p = Person("尼古拉斯", "刘能") # 把对象转换成json
s = json.dumps(p.__dict__, ensure_ascii=False) # 方案一, 转的是字典
def func(obj): return { "firstName": obj.firstName, "lastName": obj.lastName } s = json.dumps(p, default=func, ensure_ascii=False) # 方案二 转化的也是字典
print(s) #{"firstName": "尼古拉斯", "lastName": "刘能"}
f = open("movie.json", mode="r", encoding="utf-8") dic1 = json.load(f) # 当json文件中保存多个json的时候不能一次性全部都读取出来
print(dic1) f = open("movie.json", mode="r", encoding="utf-8") for line in f: line = line.strip() if line == "": # 如果是空字符跳过
continue
else: d = json.loads(line) # 一行一行的处理
print(d)
4. configparser 处理windows配置文件的 dict
import configparser config = configparser.ConfigParser() # 创建对象
config['DEFAULT'] = { # 特殊
"name":"腾讯qq木马", "time":"qq更新时间", "version":"1.0" } config['SERVER_1'] = { "IP":"192.168.1.123", "port":"12306" } config['SERVER_2'] = { "IP":"192.168.1.178", "port":"12311" } config['SERVER_3'] = { "IP":"192.168.1.176", "port":"12312" } # 写入到文件
config.write(open("qq.ini", mode="w", encoding="utf-8")) # 读取内容
config = configparser.ConfigParser() # 读取内容
config.read("qq.ini", encoding="utf-8") # 此时我们把文件中的内容读取到config
print(config['SERVER_1']['IP']) # 字典
print(config['SERVER_2']['name']) print(config.get("SERVER_3", "IP")) # 字典
for k, v in config['DEFAULT'].items(): print(k, v)