jsonpicklexmlshelve模块
Posted chqworkhome
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jsonpicklexmlshelve模块相关的知识,希望对你有一定的参考价值。
1、json.dump/json.dumps 将数据转换成json
v = json.dump(variant) //将variant中单引号变成双引号,再将变量转字符串
eg:
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = ‘numbers.json‘
with open(filename, ‘w‘) as f_obj:
json.dump(numbers, f_obj) //同 f_obj.write(json.dumps(numbers))
2、json.load/json.loads 读数据,读取的内容必须符合json规范
import json
filename = ‘numbers.json‘
with open(filename) as f_obj:
numbers = json.load(f_obj) //同 numbers=json.loads(f_obj.read())
3、pickle.dump/pickle.dumps 将数据转换成 bytes
4、pickle.load/pickle.loads 读数据,读取的内容必须是bytes
5、shelve模块
import shelve
f = shelve.open(r"testFile1")
f["name"] = "chenhaiquan"
f["name1"] = "chenhaiquan1"
f.close()
ff = shelve.open(r"testFile1")
print(ff["name"])
print(ff["name1"])
ff.close()
6、xml模块
import xml.etree.ElementTree as ET
# 解析xml文件
tree = ET.parse("testFile.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)
# 只遍历ETD节点
for node in root.iter(‘ETD‘):
print(type(node.tag) ,node.tag, node.text)
# 删除
for child in root:
isChildCompelete = False
while not isChildCompelete:
isChildCompelete = True
for i in child:
if i.tag != "ETA" and i.tag != "ETD":
isChildCompelete = False
child.remove(i)
tree.write("testFile1.xml")
# 修改
for node in root.iter("ETD"):
node.text = "去你家里吧"
node.set("update", "true")
tree.write("testFile1.xml")
# 新增
# <?xml version=‘1.0‘ encoding=‘utf-8‘?>
# <name.list>
# <name enrolled="yes">
# <age enrolled="no" />
# <sex>19</sex>
# </name>
# <name enrolled="no">
# <age />
# </name>
# </name.list>
new_xml = ET.Element("name.list")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"enrolled": "no"})
sex = ET.SubElement(name, "sex")
sex.text = "23"
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
sex.text = "19"
et = ET.ElementTree(new_xml)
et.write("testFile1.xml", encoding="utf-8", xml_declaration=True)
以上是关于jsonpicklexmlshelve模块的主要内容,如果未能解决你的问题,请参考以下文章
Python 常用模块 -- collections模块,time模块,random模块,os模块,sys模块
python内几种常用内置模块的介绍,包括time模块,datetime模块,random模块,os模块,sys模块,hashlib模块