什么叫序列化?
序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes。
一、json
是实现序列化的一个模块,用于字符串 和 python数据类型间进行转换,不仅限于字典。
Json模块提供了四个功能:dumps、dump、loads、load
import json
data = {"name":"tom","age":18,"addr":"北京"}
# 将字典data序列化成字符串
dataStr = json.dumps(data)
f = open("data.txt","w",encoding="utf-8")
# 将字典data序列化保存到文件中
json.dump(data,f)
print(dataStr)
# 将字典data字符串反序列化成字典
data = json.loads(dataStr,encoding="utf-8")
print(data)
# 从文件中反序列化成字典
with open("data.txt","r",encoding="utf-8") as f:
data = json.load(f)
print(data)
运行结果
{"name": "tom", "age": 18, "addr": "\u5317\u4eac"}
{'name': 'tom', 'age': 18, 'addr': '北京'}
{'name': 'tom', 'age': 18, 'addr': '北京'}
二、pickle
pickle也是实现序列化的一个模块,用于python特有的类型 和 python的数据类型间进行转换。
pickle模块提供了四个功能:dumps、dump、loads、load
import pickle
data = {"name":"tom","age":18,"addr":"北京"}
# 将字典data序列化成二进制数据
dataStr = pickle.dumps(data)
f = open("data.pkl","wb")
# 将字典data序列化保存到文件中w
pickle.dump(data,f)
print(dataStr)
# 将字典data二进制数据反序列化成字典
data = pickle.loads(dataStr,encoding="utf-8")
print(data)
# 从文件中反序列化成字典
with open("data.pkl","rb") as f:
data = pickle.load(f)
print(data)
运行结果
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x03\x00\x00\x00tomq\x02X\x03\x00\x00\x00ageq\x03K\x12X\x04\x00\x00\x00addrq\x04X\x06\x00\x00\x00\xe5\x8c\x97\xe4\xba\xacq\x05u.'
{'name': 'tom', 'age': 18, 'addr': '北京'}
{'name': 'tom', 'age': 18, 'addr': '北京'}
三、shelve
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
import shelve
s = shelve.open("haha.txt")
stu = {"name":"tom","age":18,"addr":"北京"}
fruit = ["apple","banana","watermelon","peach"]
# 持久化
s["stu"] = stu
s["fruit"] = fruit
s.close()
# ----------------------------------------------
s = shelve.open("haha.txt")
# 获取
stu = s.get("stu")
print(stu)
fruit = s.get("fruit")
print(fruit)
结果:
持久化文件会生成三个文件haha.txt.bat、haha.txt.bak、haha.txt.dir
{'name': 'tom', 'age': 18, 'addr': '北京'}
['apple', 'banana', 'watermelon', 'peach']
四、xml
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
xml的格式如下,就是通过<>节点来区别数据结构的:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
#遍历xml文档
for child in root:
print(child.tag, child.attrib)
for i in child:
print(i.tag,i.text)
#只遍历year 节点
for node in root.iter('year'):
print(node.tag,node.text)
修改和删除xml文档内容
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
#修改
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set("updated","yes")
tree.write("xmltest.xml")
#删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('output.xml')
自己创建xml文档
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
四、json、pickle、shelve、xml比较
json:跨语言、体积小;只能支持int\str\list\tuple\dict
pickle:专为python设计,支持python所有的数据类型;只能在python中使用,存储数据占空间大
shelve:通过key、value将数据持久化到内存,可以持久化python支持的一切数据类型
xml:跨语言、体积大