python--(常用模块-2序列化)

一.序列化:

把对象打散成bytes或者字符串。 方便存储和传输 序列化
  把bytes或者字符串转换回对象。 反序列化

# dumps 序列化。 把对象转化成bytes
# loads 反序列化。 把bytes转化成对象
# dump 序列化。 把对象转化成bytes并写入文件
# load 反序列化。把文件中的bytes读取。转化成对象

 

二.pickle(比较重要)

  把python中所有的对象都可以转化成bytes。进行存储和传输

  

1 # import pickle
 2 # class Cat:
 3 #     def __init__(self,name,age):
 4 #         self.name = name
 5 #         self.age = age
 6 #
 7 #     def catchMouse(self):
 8 #         print(self.name,"抓老鼠")
 9 # c = Cat("jerry",18)
10 # bs = pickle.dumps(c) #序列化一个对象
11 # print(bs)#一堆二进制,看不懂
12 #
13 # cc = pickle.loads(bs) #把二进制反序列化成我们的对象
14 # cc.catchMouse()
15 
16 
17 
18 # lst = [Cat("jerry",Cat("tommy",20),Cat("alpha",21))]
19 #
20 # f = open("cat",mode = "wb")
21 # pickle.dump(lst,f)  #写入到文件中
22 #
23 # f = open("cat",mode = "rb")
24 # l1 = pickle.load(f)  #从文件中读取
25 # for i in l1:
26 #     i.catchMouse()

 

三.shelve 

shelve提供python的持久化操作. 什么叫持久化操作呢? 说⽩话,就是把数据写到硬盘上.
  在操作shelve的时候非常的像操作⼀个字典. 这个东⻄到后期. 就像redis差不多.

1 import shelve
 2 
 3 # 打开一个文件
 4 # f = shelve.open("大阳哥", writeback=True)
 5 # f['jj'] = "林俊杰"
 6 # f['dyg'] = "大阳哥"
 7 # f['zzr'] = "周芷若"
 8 
 9 # f = {}
10 # 像操作字典一样操作文件
11 # f["jay"] = "周杰伦"
12 # print(f['jay'])
13 
14 # f["jay"] = {'name': "周杰伦", 'age': 38, "hobby": "吃喝拉撒睡"}
15 
16 # f['jay']['name'] = "胡辣汤"
17 # print(f['jay']['name'])
18 # print(f['jay'])
19 
20 
21 # f.close()
22 
23 f = shelve.open("大阳哥")
24 # print(f.keys())
25 # for k in f.keys(): # 可以获取到所有的key
26 #     print(k)
27 #
28 # for k in f:
29 #     print(k)
30 #
31 # for k, v in f.items():
32 #     print(k, v)

 

 

四.json(重点)  

json是我们前后端交互的枢纽. 相当于编程界的普通话. ⼤家沟通都⽤
   json. 为什么这样呢? 因为json的语法格式可以完美的表⽰出⼀个对象. 那什么是json: json全
   称javascript object notation. 翻译过来叫js对象简谱.

1 # import json
 2 # dic = {"a":"女王","b":"萝莉","c":"小仙女"}
 3 # s = json.dumps(dic) #把字典转换成json字符串
 4 # print(s)
 5 # #{"a": "\u5973\u738b", "b": "\u841d\u8389", "c": "\u5c0f\u4ed9\u5973"}
 6 #
 7 # import json
 8 # dic = {"a":"女王","b":"萝莉","c":"小仙女"}
 9 # s = json.dumps(dic,ensure_ascii=False) #ensure_ascii=False 去asxiii码
10 # print(type(s),s)
11 # #<class 'str'> {"a": "女王", "b": "萝莉", "c": "小仙女"}
12 #
13 # import json
14 # s =  '{"a": "⼥王", "b": "萝莉", "c": "小仙女"}'
15 # dic = json.loads(s)
16 # print(type(dic),dic)
17 # #<class 'dict'> {'a': '⼥王', 'b': '萝莉', 'c': '小仙女'}
18 
19 
20 # #写入文件
21 # dic = {"a": "⼥王", "b": "萝莉", "c": "⼩清新"}
22 # f = open("test.json", mode="w", encoding="utf-8")
23 # json.dump(dic, f, ensure_ascii=False) # 把对象打散成json写⼊到⽂件中
24 # f.close()
25 #
26 # #读取文件
27 # f = open("test.json", mode="r", encoding="utf-8")
28 # dic = json.load(f)
29 # f.close()
30 # print(dic)
31 
32 
33 # 注意我们可以向同一个文件写入多个json串,但是读不行.
34 # 写入的时候
35 # 1. 循环
36 # 2. 用dumps把字典转化成字符串, 然后手工在后面加一个\n
37 # 3. 写出
38 # f = open("new_menu.json", mode="w", encoding="utf-8")
39 # lst = [{"a": "胡辣汤"},{"b":"吱吱冒油的大猪蹄子"},{"c": "盖浇饭"},{"d":"马拉"},{"e":"法国大蜗牛"}]
40 # for el in lst:
41 #     s = json.dumps(el, ensure_ascii=False) + "\n"
42 #     f.write(s)
43 #
44 # f.flush()
45 # f.close()
46 
47 
48 # 读取的时候
49 # 1. for line in f:
50 # 2. strip()去掉空白
51 # 3. loads()变成字典
52 
53 # f = open("new_menu.json", mode="r", encoding="utf-8")
54 # for line in f:
55 #     line = line.strip()
56 #     dic = json.loads(line)
57 #     print(dic)

 

六.configparser

  该模块适用于配置⽂件的格式与windows ini⽂件类似,可以包含一个或多个节(section)每个节
  可以有多个参数(键=值). 首先, 我们先看一个xxx服务器的配置文件

1 [DEFAULT] [DEFAULT]
 2 ServerAliveInterval = 45
 3 Compression = yes
 4 CompressionLevel = 9
 5 ForwardX11 = yes
 6 [[bitbucket.org bitbucket.org]]
 7 User = hg
 8 [[topsecret.server.com topsecret.server.com]]
 9 Port = 50022
10 ForwardX11 = no

我们用configparser就可以对这样的文件进行处理.首先,是初始化

python bytes bytesarray 转化 python将bytes转为对象_反序列化

python bytes bytesarray 转化 python将bytes转为对象_序列化_02

1 import configparser
 2 config = configparser.ConfigParser()
 3 config['DEFAULT'] ={ "sleep": 1000,
 4   "session-time-out": 30,
 5   "user-alive": 999999
 6 }
 7 config['TEST-DB'] = {
 8   "db_ip": "192.168.17.189",
 9   "port": "3306",
10   "u_name": "root",
11   "u_pwd": "123456"
12 }
13 config['168-DB'] = {
14   "db_ip": "152.163.18.168",
15   "port": "3306",
16   "u_name": "root",
17   "u_pwd": "123456"
18 }
19 config['173-DB'] = {
20   "db_ip": "152.163.18.173",
21   "port": "3306",
22   "u_name": "root",
23   "u_pwd": "123456"
24 }
25 f = open("db.ini", mode="w"
26 config.write(f) # 写⼊⽂
27 f.flush()
28 f.close()

View Code

读取文件信息

python bytes bytesarray 转化 python将bytes转为对象_反序列化

python bytes bytesarray 转化 python将bytes转为对象_序列化_02

1 config = configparser.ConfigParser()
 2 config.read("db.ini") # 读取⽂
 3 print(config.sections()) # 获取到section. 章节...DEFAULT是给每个章节都配备的信
 4 print(config.get("DEFAULT", "SESSION-TIME-OUT")) # 从xxx章节中读取到xxx信
 5 # 也可以像字典⼀样操作
 6 print(config["TEST-DB"]['DB_IP'])
 7 print(config["173-DB"]["db_ip"])
 8 
 9 for k in config['168-DB']:
10   print(k)
11 for k, v in config["168-DB"].items():
12   print(k, v)
13 
14 print(config.options('168-DB')) # 同for循环,找到'168-DB'下所有
15 print(config.items('168-DB')) #找到'168-DB'下所有
16 
17 print(config.get('168-DB','db_ip')) # 152.163.18.168 get⽅法Section下的
18 key对应的value

View Code

增删改操作:

python bytes bytesarray 转化 python将bytes转为对象_反序列化

python bytes bytesarray 转化 python将bytes转为对象_序列化_02

1 # 先读取. 然后修改. 最后写回⽂件
 2 config = configparser.ConfigParser()
 3 config.read("db.ini") # 读取⽂
 4 # 添加⼀个章节
 5 # config.add_section("189-DB")
 6 # config["189-DB"] = {
 7 # "db_ip": "167.76.22.189",
 8 # "port": "3306",
 9 # "u_name": "root",
10 # "u_pwd": "123456"
11 # }
12 
13 # 修改信息
14 config.set("168-DB", "db_ip", "10.10.10.168")
15 # 删除章节
16 config.remove_section("173-DB")
17 # 删除元素信息
18 config.remove_option("168-DB", "u_name")
19 # 写回⽂件
20 config.write(open("db.ini", mode="w"

View Code