序列化
一.pickle
以bytes 形式操作
pickle.dumps(obj) #打碎 得到了btyes 类型
pickle.loads(pickle.dumps(obj)) #转化对象(该对象的类必须存在)
f=open("filename","ab")
pickle.dump(obj,f) #往文件中一个一个存对象
f=open("filename","rb")
pickle.load(f) #一个一个获取对象
import pickle class Cat: def __init__(self,name,color): self.name=name self.color=color def chi(self): print("%s会吃老鼠"%self.name) # c1=Cat("汪峰1","黑色") # c2=Cat("汪峰2","黑色") # c3=Cat("汪峰3","黑色") # c4=Cat("汪峰4","黑色") # bs=pickle.dumps(c) # print(bs) # cc=pickle.loads(bs) # cc.chi() # print(cc.name) # print(cc.color) # pickle.dump(c1,open("cat.dat","wb")) #将对象以bytes类型写入到文件 # b=pickle.load(open("cat.dat","rb")) #将文件的内容读取 # print(b.name) # b.chi() # lst=[c1,c2,c3,c4] # pickle.dump(lst,open('cat.dat',"wb")) lst=pickle.load(open('cat.dat',"rb")) for cat in lst: cat.chi()
二.shelve 相当文件字典
注意点:
1.d=shelve("filename") #filename 要存入的文件名
d['name']="deng" #设置属性
d.close()
2.如何要修改下一层字典中的属性的话,需要:
d=shelve("filename",writeback=True) # writeback=True 表示回写
d["liu"]={'wf':"zhang","age":23} #设置熟悉
d["liu"]["wf"]="tao" #修改内层字典的属性
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() d = shelve.open("sylar") for k, v in d.items(): print(k, v) print(type(d))
三.configparser 操作ini 文件
import configparser #配置文件 # con=configparser.ConfigParser() #创建对象 # con["DEFAULT"]={ # "name":"腾讯木马", # "time":'腾讯更新时间', # "version":"1.0" # } # con["SERVER_1"]={ # "IP":"192.168.1.123", # "port":"10068" # } # con["SERVER_2"]={ # "IP":"192.168.1.134", # "port":"10078" # } # con["SERVER_3"]={ # "IP":"192.168.1.127", # "port":"10069" # } # #写入到文件 # con.write(open("qq.ini","w",encoding="utf-8")) #读取文件中的内容 con=configparser.ConfigParser() #创对象 con.read("qq.ini",encoding="utf-8") # print(con["SERVER_1"]) # print(con["SERVER_1"]["name"]) # for el in con["SERVER_1"]: # print(el) # print(con.options("SERVER_1")) #列表的形式返回该章节下的所有key 包括第一个对象默认的key #增删改 #增加章节 con.add_section("SERVER_4") con["SERVER_4"]={ "IP":"196.168.11", "port":"10234" } #修改 con.set("SERVER_1","IP","192.168.100000") print(con["SERVER_1"]["IP"]) #删除章节 con.remove_section("SERVER_3") #删除元素 con.remove_option("SERVER_2","port") #写回文件 con.write(open("qq.ini","w",encoding="utf-8"))
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")) #操作ini 文件 # # # # 读取内容 # 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) # config = configparser.ConfigParser() # # 读取内容 # config.read("qq.ini", encoding="utf-8") # 此时我们把文件中的内容读取到config # config['SERVER_1']['NAME'] = "哈哈哈" # config.write(open("qq.ini", mode="w", encoding="utf-8"))
四.json
1.
json.dumps(dic,ensure_ascii=False) #ensure_ascii 默认ascii,显示中文需要 设置为false
json.loads(json字符串) 将json字符串转化为字典
对象转化成json字符串 两种方式
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
p=Person("刘德华",23)
将对象 p 转化成json
方案一:
s=json.dumps(p.__dict__)
方案二:
def func(obj): #自定义 函数得到所需要的字符串字典格式 ,穿
return {"name":obj.name,"age":obj.age}
s=json.dumps(p,default=func,ensure_ascii=False)
将json对象还原回对象
s='{"name": "刘能", "age": 12}'
def func(dic):
return Person(dic["name"],dic["age"])
p=json.loads(s,object_hook=func)
2.json 写文件,读文件相关
1.写入文件:
dic={"name":"汪峰","age":123,"hobby":{"体育":'a','书':"射雕"}}
f=open("userinfo","w",encoding="utf-8")
json.dump(dic,f,ensure_ascii=Flase,indent=4) #写入文件,indent缩进为4个字符
2.文件中读取
f=open("userinfo","r",encoding="utf-8")
dic=json.load(f)
3.重点:(用的最多)
1.字典以json字符串的格式,循环一行一行写入文件
lst=[dic1,dic2,dic3]
for dic in lst:
s=json.dumps(dic,ensure_ascii=False)
f.write(s+"\n")
2.for line in f: 一行行读取文件,得到dic=json.loads(line.strip())
import json # # 准备一个字典 # dic = {"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": False, "e": None} # # python中可以直接把字典或者列表转化成json # s = json.dumps(dic, ensure_ascii=False) # pickle # print(type(s)) # print(s) # s = '{"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": false, "e": null}' # d = json.loads(s) # 把json转化成字典 # print(d) # print(type(d)) # 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) # 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) dic1 = {"name":'毒液', "评分": "0.9"} dic2 = {"name":'与神同行', "评分": "10"} dic3 = {"name":'看不见的客人', "评分": "9.5"} # lst = [dic1, dic2, dic3] # f = open("movie.json", mode="w", encoding="utf-8") # for d in lst: # s = json.dumps(d, ensure_ascii=False) # f.write(s+"\n") # 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)