如果想要将python文件永久保存,除了可以保存到数据库中,也可以使用json,pickle等模块,这些模块可以将数据存储到硬盘中,也可以用于传输使用
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"]
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")
输出的文件
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
删除该节点
创建一个元素结点
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)
import pickle
将字符串转换为特定类型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)
将特定字符串转换为相应的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一般用于网络传输
传入文件对象 将对象存入文件中,文件必须为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)
文件模式为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)
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)
#导入模块
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)
文件格式*.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用 []
属性赋值用 = 或:
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 val3:
print("val1",val1)
#val1 50
print("val2",val2)
#val2 male
print("val3",val3)
#val3 50
必须写入文件中才生效
sec = config.remove_section("Options")
config.write(open("MY2.INI","w"))
config.remove_option("voice","hight")
config.write(open("MY2.INI","w"))
config.remove_option删除一个option
config.remove_section 删除一个section
sec = config.has_section("LAN")
#False
config.has_option("voice","hight")
config.add_section("LAN")
config.write(open("MY2.INI","w"))
config.set('Options','color',"red")
#传入section ooption value 值必须为字符串
config.write(open("MY2.INI","w"))