序列化 把对象打散成二进制字节 bytes
1. pickle 把一个对象转化成bytes写入到文件
pickle.dumps() 把对象转换成bytes
pickle.loads() 把bytes转化成对象
pickle.dump() 把对象转换成bytes. 写入到文件
pickle.load() 把文件中的bytes读取. 转化成对象
2. shelve 小型数据库, redis, mongodb, dict
当成字典来用
writeback=True
3. json 以前用xml 先在用json
json.dumps() 把字典转换成json字符串
json.loads() 把json字符串转化成字典
json.dump() 把字典转换成json字符串. 写入到文件
json.load() 把文件中的json字符串读取. 转化成字典
default = 把对象转化成字典. 需要自己写转换过程
object_hook = 把字典转化成对象. 需要自己写转换过程
ensure_ascii = False 可以处理中文
4. configparser 处理windows配置文件的 dict
class User:
# def __init__(self, username, password):
# self.username = username
# self.password = password
#
#
# class Admin:
# def regist(self):
# uname = input("注册账号-->")
# pswd = input("密码-->")
# user =User(uname,pswd)
# pickle.dump(user,open("list_user","ab"))
# print("注册成功!")
#
# def login(self):
# uname = input("--登录账号-->")
# pswd = input("--密码-->")
# f = open("list_user","rb")
#
# while 1:
# try:
# u = pickle.load(f)
# if u.username == uname and u.password == pswd:
# print("登录成功")
# break
# except Exception as e:
# print("登录失败!")
# break
#
# u1 = Admin()
# u1.regist()
# u1.regist()
#
# u1.login()
# ----------------------------------
# import shelve
#
# d = shelve.open("pig") #文件类型的字典
# d['ajx'] = "阿J斯"
# d.close()
#
# d = shelve.open("pig")
# print(d['ajx'])
# d.close()
#
# d = shelve.open("pig") #文件类型的字典
# d['ajx'] = {"name":"阿J斯","age":18}
# d.close()
# ----------------------------------
import json
# dikt={"A":"西瓜","B":"草莓","C":"香蕉","D":"菠萝"}
# J = json.dumps(dikt,ensure_ascii=False)
# print(J)
# print(type(J))
# print("*" * 80)
# s = '{"A":"西瓜","B":"草莓","C":"香蕉","D":"菠萝"}'
# J1 = json.loads(s)
# print(J1)
# print(type(J1))
# ----------------------------------
# dikt2 = {"A": "西瓜", "B": "草莓", "C": "香蕉", "D": "菠萝"}
# f = open("nainiu.json", "w", encoding="utf8")
# json.dump(dikt2, f, ensure_ascii=False, indent=4)
#
# f1 = open("nainiu.json", "w", encoding="utf8")
# f2 = json.load(f1)
# print(f2)
# ----------------------------------
# class PP:
# def __init__(self, F_name, L_name):
# self.F_name = F_name
# self.L_name = L_name
#
#
# p1 = PP("蒙娜丽莎", "江小白")
#
#
# # 把对象转化成json
# # s = json.dumps(p1.__dict__, ensure_ascii=False)
# # print(s)
#
# def func(obj):
# return {
# "firstName": obj.F_name,
# "lastName": obj.L_name
# }
#
#
# # s = json.dumps(p1, default=func, ensure_ascii=False)
# # print(s)
#
#
# # ----------------------------------
# s = '{"firstName": "蒙娜丽莎", "lastName": "江小白"}'
# def funk():
# return PP(dic["firstName"],dic["lastName"])
#
# p = json.loads(s,object_hook=func)
# print(p.lastName,p.lastName)