文章目录

  • python持久化存储模块
  • 1.shelve模块
  • 导入模块
  • 增加、修改数据
  • 查询
  • 删除
  • 2.xml模块
  • 导入模块
  • 读取树
  • 获取根节点
  • 获取根节点标签
  • 遍历文档
  • 遍历一个节点
  • 修改节点信息
  • 删除node
  • 创建一个xml文档
  • 3.pickle模块
  • 导入模块
  • dumps
  • loads
  • dump,load
  • 4.json模块
  • dump,load
  • dumps,loads
  • 5.configparser
  • 5.0 模块示例
  • 5.0 配置文件示例
  • 5.1读
  • 读取文件
  • 读取内容
  • 获取该区域下的属性
  • 5.2 删除
  • 删除section
  • 删除opttion
  • 5.3 判断
  • 判断是否有section
  • 判断是否有option
  • 5.4 设置
  • 设置section
  • 设置option


python持久化存储模块

如果想要将python文件永久保存,除了可以保存到数据库中,也可以使用json,pickle等模块,这些模块可以将数据存储到硬盘中,也可以用于传输使用

1.shelve模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

导入模块

import shelve 打开文件
f = shelve.open("shelve_test")

增加、修改数据

li = [1,2,3,4]  
f["li"] = li

查询

f["li"]

删除

del f["li"]

2.xml模块

导入模块

import xml.etree.ElementTree as ET

读取树

解析一个
tree = ET.parse("xmltest.xml")

获取根节点

root = tree.getroot()

获取根节点标签

print(root.tag)

遍历文档

for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag,i.text)

child.tag 孩子节点的标签
child.attrib 孩子节点的属性

遍历一个节点

for node in root.iter('year'):
    print(node.tag,node.text)

root.iter 在所有的孩子结点中找year结点

修改节点信息

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.text 获取节点中的内容
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')

country.find 寻找一个匹配的
root.findall 寻找所有匹配的
root.remove 删除该节点

创建一个xml文档

创建一个元素结点
new_xml = ET.Element("namelist")

创建一个子元素结点 attrib={} 属性字典

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)

3.pickle模块

导入模块

import pickle

dumps

将字符串转换为特定类型bytes

data = {"k1":123,"k2":"hello"}
p_str = pickle.dumps(data)
print(p_str)
#b'\x80\x03}q\x00(X\x02\x00\x00\x00k1q\x01K{X\x02\x00\x00\x00k2q\x02X\x05\x00\x00\x00helloq\x03u.'
#存储该特定形式   必须要用*.pk  二进制模式wb
with open("result.pk","wb") as fp:
    pickle.dump(data,fp)

loads

将特定字符串转换为相应的python格式

with open("result.pk","rb") as f:
    p_str = f.read()
p_str = pickle.loads(p_str)
print(p_str)
#{'k1': 123, 'k2': 'hello'}

dumps,loads一般用于网络传输

dump,load

传入文件对象 将对象存入文件中,文件必须为wb模式 二进制模式

li = [i**2 for i in range(10)]
with open("result1.pk","wb") as f:
    pickle.dump(li,f)
#load 传入文件对象,必须为rb模式  二进制模式
with open("result.pk","rb") as f:
    p_str = pickle.load(f)

4.json模块

dump,load

文件模式为w 文本模式

with open("result.json","w") as f:
    json.dump(dt,f)
load模式  文件模式为r 文本模式
with open("result.json","r",encoding="utf-8") as f:
    p_str = json.load(f)

dumps,loads

dt_j = json.dumps(dt)
{"123": "abc", "func": "dfs"}
#load 文本模式
with open("result1.json","r",encoding="utf-8") as f:
    dt_j = f.read()
dt_1 = json.loads(dt_j)

5.configparser

5.0 模块示例

#导入模块  
import configparser
config = configparser.ConfigParser()

#读取文件
config.read("RA2MD.INI")

#调用sections方法(默认不会读取default)
print(config.sections())

#判断元素是否在该section列表内
print('SendDelay' in config)
print('LAN' in config)

#获取元素值
print(config["Video"]["ScreenWidth"])
print(config["Video"]["ScreenHeight"])

#遍历video的section里面所有的key
for key in config["Video"]:
    print(key)

5.0 配置文件示例

文件格式*.INI

[voice]
hight = 50
family:male

[Video]
VideoBackBuffer=no
AllowVRAMSidebar=no
AllowHiResModes=yes
ScreenWidth=1920
ScreenHeight=1080
StretchMovies=yes

[Options]
GameSpeed=0
Difficulty=0

section用 []
属性赋值用 = 或:

5.1读

读取文件

import configparser
config = configparser.ConfigParser()
config.read("MY.INI")

读取内容

#获取所用section
sec = config.sections()
print(sec)
#['voice']

获取该区域下的属性

options = config.options('voice')
print(options)
#['hight', 'family']

val1 = config.get("voice","hight")
val2 = config.get("voice","family")
val3 = config.getint("voice","hight")
print("val1",type(val1),"val3:",type(val3))
#val1 <class 'str'> val3: <class 'int'>
print("val1",val1)
#val1 50
print("val2",val2)
#val2 male
print("val3",val3)
#val3 50

5.2 删除

必须写入文件中才生效

删除section

sec = config.remove_section("Options")
config.write(open("MY2.INI","w"))

删除opttion

config.remove_option("voice","hight")
config.write(open("MY2.INI","w"))

config.remove_option删除一个option
config.remove_section 删除一个section

5.3 判断

判断是否有section

sec = config.has_section("LAN") 
#False

判断是否有option

config.has_option("voice","hight")

5.4 设置

设置section

config.add_section("LAN")
config.write(open("MY2.INI","w"))

设置option

config.set('Options','color',"red")
#传入section ooption value   值必须为字符串
config.write(open("MY2.INI","w"))