python常用模块02

一.什么是序列化

​ 在数据存储和网络传输的时候,需要对我们的对象进行处理,处理方便存储和传输的数据格式,这个过程叫序列化。不同序列,处理的方式不同,但目的想相同,都是为达到方便存储、传输。序列化是为了解决对象的传输问题。

​ 在python中存在三种序列化的方案

  1. pickle python 任意数据类型转化成bytes并写入文件中。同样也可以将文件bytes转换回我们python的数据,这个过程叫反序列化。
  2. shelve 简单另类的一种序列化,有点类似redis可以作为一种小型数据使用
  3. json将pythoh中常见的字典,列表转化成字符串,是前后端数据交换使用频率最高的的一种数据格式

二.pickle

​ pickle就是将python对象写入文件中一种解决方案,但写入的是bytes。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#生成一只猫,今天我要把猫打扁。让他变成机器猫。
import pickle
#
class Cat:
def __init__(self,name,age):
self.name = name
self.age = age
def catchMouse(self):
print(self.name,self.age,'抓老鼠')
#序列化
cat = Cat('tom',12) #生成一个对象
bs = pickle.dumps(cat) #把对象转化bytes 序列化
print(bs) #
#对象变成bytes了
''' b'\x80\x03c__main__\nCat\nq\x00)\x81q\x01}q\x02(X\x04\x00\x00\x00nameq\x03X\x03\x00\x00\x00tomq\x04X\x03\x00\x00\x00ageq\x05K\x13ub.'
'''
#反序列化
# #把bytes 转换回对象 ,反序列化

cf = pickle.loads(bs)
cf.catchMouse() #猫 还可以抓抓老鼠



#对字典的巡序列化
dic = {"tom":"贾老练",'jj':"渣渣"}

bs = pickle.dumps(dic)
print(bs)
d = pickle.loads(bs)
print(d

Pickle中dumps 可以序列化一个对象, loads反序列化,dump可以将对象写入文件

1
2
3
4
5
6
7
8

# f = open('cat',mode='wb') #将猫写入文件中
# pickle.dump(tom,f)

rf = open('cat',mode='rb') # 读取文件中猫
cc = pickle.load(rf)
cc.catchMouse() #让猫抓老鼠

pickle多个对象写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#多个对象写入文件
lst = [Cat('jerry',20),Cat('jek',14),Cat('blue',22)]
#
f = open('cat',mode='wb') #写入文件中

#for el in lst:
# pickle.dump(el,f)
#f.close()

#从文件读取对象;
f = open('cat',mode='rb') #从文件读取对象
while 1:
try:
c1 = pickle.load(f)
c1.catchMouse()
except EOFError:
break
  • 另一种推荐方式读取写入

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #多个对象装入list中,然后读取写入都用着list

    #写入
    lst = [Cat('jerry',20),Cat('jek',14),Cat('blue',22)]
    f = open('cat',mode='wb') #打开文件
    pickle.dump(lst,f)


    #读取

    f = open('cat',mode='rb')
    ll = pickle.load(f)
    for el in ll:
    el.catchMouse()

    #

二.shelve

​ shelve提供python持久化操作。持久化往往依赖于数据库,为了长期存储。在操作shelve像是操作python中字典。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

import shelve

shelf = shelve.open("ss")

shelf['arm'] = '馒头'
print(shelf['arm'])

shelf.close()

#文件

#打开一个文件
f = shelve.open("info", writeback=True) #动态的将修改信息写入文件。
f['jj'] = "老王"
f['nk'] = "脑壳"
f['zds'] = "张德帅"

#f = {}
#像操作字典一样操作文件
f["jay"] = "周杰伦"
print(f['jay'])

f["jay"] = {'name': "周杰伦", 'age': 38, "hobby": "吃喝拉撒睡"}
f['jay']['name'] = "胡辣汤"
print(f['jay']['name'])
print(f['jay'])


for k,v in f.items():
print(k,v)

f.close()



# print(f.keys())
# for k in f.keys(): # 可以获取到所有的key
# print(k)
#
# for k in f:
# print(k)
#
# for k, v in f.items():
# print(k, v)

四.json

​ json是我们前后端交互的枢纽。因为json的语法格式可以完美表示一个对象。json 全称(javascript object natation)翻译js对象简谱

在python中这玩意就字典。在JavaScript叫json

1
2
3
4
5
6
7
8
9
10
11

wf = {
"name": "汪峰",
"age": 18,
"hobby": "抢头条",
"wife": {
"name": "子怡",
"age": 19,
"hobby":["唱歌", "跳舞", "演戏"]
}
}

因为是python中写的,前端需要js来解析json。所以需要将程序产生的字典转化成json格式的json字符串。

1
2
3
4
5
6
7
8

import json
dic = {"a":'普罗米修斯','b':'异性','c':"星际穿越"}
strd = json.dumps(dic)
print(strd)
#输出结果
#{"a": "\u666e\u7f57\u7c73\u4fee\u65af", "b": "\u5f02\u6027", "c": "\u661f\u9645\u7a7f\u8d8a"}

​ 结果很不友好,处理中文需要dumps的一个参数ensure_ascii=False ,转换字符son.dumps

1
2
3
4
5
6
import json
dic = {"a":'普罗米修斯','b':'异性','c':"星际穿越"}
b = json.dumps(dic,ensure_ascii=False) #字典转化为字符串
print(type(b),b)
#输出结果
#<class 'str'> {"a": "普罗米修斯", "b": "异性", "c": "星际穿越"}

​ 处理前端传过来的json字符串转化为字典利用json.loads参数

1
2
3
4
5
6
import
s = '{"a":'普罗米修斯','b':'异性','c':"星际穿越"}'
dic = json.loads(s) #字符串解析成字典
print(type(dic),dic)
#输出结果
#<class 'dict'> {'a': '普罗米修斯', 'b': '异性', 'c': '星际穿越'}
json写入读取

​ json序列化结果写入文件中。

1
2
3
4
5
6
7
8
import json

dic = {"a":'普罗米修斯','b':'异性','c':"星际穿越"}

f = open('test.json',mode='w',encoding='utf-8')
json.dump(dic,f,ensure_ascii=False)
f.close()

​ 读取文件中一个json

1
2
3
4
5
6
7

rf = open('test.json',mode='r',encoding='utf-8')
rdic = json.load(rf)
rf.close()
print(type(rdic),rdic)
#输出结果
#<class 'dict'> {'a': '普罗米修斯', 'b': '异性', 'c': '星际穿越'}

注意 可以向一个文件写入多个json串,但读不行。

1
2
3
4
5
6
7
8
9
10
11
12
13
import json
lst = [{'a':1},{'b':'包子'},{"c":'馒头'}]
f = open('test.json',mode='w',encoding='utf-8')

for el in lst:

json.dump(el,f,ensure_ascii=False)

f.close()
#输出结果,内容都在一行无法正常读取。
#{"a": 1}{"b": "包子"}{"c": "馒头"}


  • 解决方案

    对每一行进行处理,把dump 换成dumps

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28

    import json

    lst = [{'a':1},{'b':'包子'},{"c":'馒头'}]

    f = open('test.json',mode='w',encoding='utf-8')

    for el in lst:
    elo = json.dumps(el,ensure_ascii=False) + "\n" # 将字典转为json字符串
    f.write(elo)

    f.close()



    #读取


    import json

    f = open('test.json',mode='r',encoding='utf-8')

    for line in f:
    dic = json.loads(line.strip()) #逐行读取json字符串,转换为字典
    print(dic)
    f.close()


五.configparser模块

​ 该模块用于配置文件的格式与windows ini文件类似,可以包含多个章节(section)每个可以节可以有多个参数

1
2
3
4
5
6
7
8
9
10
11
12
[DEFAULT] 
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

import configparser

conf = configparser.ConfigParser()
conf['DEFAULT'] = {
'session-time-out':30,
'user-alive':60,
'connect-alive':10
}

conf['172-DB'] = {
'ip':'172.16.10.20',
'port': "3306",
'username':'root',
"password": "root"


}
conf['192-DB'] = {
'ip':'192.168.10.10',
'port': "3306",
'username':'root',
"password":'toor'
}

f = open('db.ini',mode='w')
conf.write(f) # 写入文件
f.flush()
f.close()

读取文件信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

import configparser

conf = configparser.ConfigParser()
conf.read('db.ini')

print(conf.sections()) # 获取章节keys()
print(conf['172-DB']['ip']) #跟字典一样

for k,v in conf['172-DB'].items():
print(k,v)

for key in conf['192-DB'].values():
print(key)

​ 增删改查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#增删改查

import configparser

conf = configparser.ConfigParser()

#添加一个章节
conf.read('db.ini') #读取文件

conf.add_section('10-DB')
#添加章节信息
conf['10-DB'] = {
"ip": '10.15.20.12',
'user': 'root',
'psw': 'toor',
}
conf.write(open("db.ini", mode="w"))

修改信息
conf.set('10-DB',"ip",'192.168.255.255')

#删除章节
conf.remove_section("10-DB")

#删除元素信息
conf.remove_option('10-DB','psw')



#最后都需要写回文件
conf.write(open("db.ini", mode="w"))



本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!