json, pickle, xml, shelve module

1, json.dump / json.dumps convert the data into json
v = json.dump (variant) // single variant will become double quotation marks, and then to String variables
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))
 
SUMMARY 2, json.load / json.loads read data, the read must comply with specifications 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 convert the data into bytes
 
4, pickle.load / pickle.loads read data bytes must be read content
 
5, shelve module
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 module
import xml.etree.ElementTree as ET
 
# Parse xml file
tree = ET.parse("testFile.xml")
root = tree.getroot ()
print(root.tag)
 
# Traversing xml document
for child in root:
print(child.tag, child.attrib)
for i in child:
print(i.tag, i.text)
 
# ETD node traversal only
for node in root.iter('ETD'):
print(type(node.tag) ,node.tag, node.text)
 
# Delete
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")
 
# Change
for node in root.iter("ETD"):
node.text = "You go home now."
node.set("update", "true")
 
tree.write("testFile1.xml")
 
New #
# <?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"
 
and = ET.ElementTree (new_xml)
et.write("testFile1.xml", encoding="utf-8", xml_declaration=True)
 
 
 

Guess you like

Origin www.cnblogs.com/chqworkhome/p/10954739.html