本节主要内容
1. 什么是序列化
2. pickle(重点)
3. shelve
4. json(重点)
5. configparser模块
⼀一. 什么是序列列化
在我们存储数据或者⽹网络传输数据的时候. 需要对我们的对象进⾏行行处理理. 把对象处理理成 ⽅方便便存储和传输的数据格式. 这个过程叫序列列化. 不同的序列列化, 结果也不同. 但是⽬目的是⼀一 样的. 都是为了了存储和传输.
在python中存在三种序列化的方案.
1. pickle. 可以将我们python中的任意数据类型转化成bytes并写入到⽂文件中. 同样也 可以把⽂文件中写好的bytes转换回我们python的数据. 这个过程被称为反序列列化
2. shelve. 简单另类的⼀一种序列化的方案. 有点儿类似后面我们学到的redis. 可以作为 ⼀种小型的数据库来使⽤用
3. json. 将python中常见的字典, 列列表转化成字符串. 是目前前后端数据交互使用频率 最高的一种数据格式.
# def __init__(self, name, color):
# self.name = name
# self.color = color
#
# def chi(self):
# print("%s猫会吃老鼠" % self.name)
#
# bs = pickle.dumps(c) # 把一个对象转化成bytes
# print(bs)
class User: def __init__(self, username, password): self.username = username self.password = password class client: def regist(self): uname = input("please input your username:") pwd = input("please input your password:") user = User(uname, pwd) pickle.dump(user, open("userinfo", mode="ab")) print("regist successful!!!") def login(self): uname = input("please input your username:") pwd = input("please input your password:") f = open("userinfo", mode="rb") while 1: try: u = pickle.load(f) # 从文件里把对象拿出来 if u.username == uname and u.password == pwd: print("login successful !!") break except Exception as e: print("login failed !!!") break c = client() # c.regist() # c.regist() # c.regist() # c.regist() c.login()
三. shelve
shelve提供python的持久化操作. 什叫持久化操作呢? 说⽩白话,就是把数据写到硬盘上. 在操作shelve的时候非常的像操作⼀一个字典. 这个东⻄西到后期. 就像redis差不多.
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模块
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) # 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(重点)
终于到json了了. json是我们前后端交互的枢纽. 相当于编程界的普通话. ⼤大家沟通都⽤用 json. 为什什么这样呢? 因为json的语法格式可以完美的表⽰示出⼀一个对象. 那什什么是json: json全 称javascript object notation. 翻译过来叫js对象简谱. 很复杂是吧? 来上⼀一段我们认识的代 码:
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+" ") # 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)