JSON & Pickle Module (serialized)
Both JSON and Pickle are serialized memory data to a file
The difference between JSON and Pickle is:
- JSON is common to all languages, but can only serialize the most basic data types (strings, dictionaries, lists), such as functions, classes, and Python dates cannot be serialized
- Pickle can serialize almost all of Python's data types
If all two programs require interactive memory data, if the Python language is the case, complex interactions with pickle.
Two modules for serialization
- JSON, used to convert between string and Python data types
- Pickle for conversion between Python-specific types and Python data types
The JSON module provides four functions: dumps, dump, loads, load
The Pickle module provides four functions: dumps, dump, loads, load
Dumps and dump differences:
| 1234 |
pickle.dump(info,f)#print(pickle.dumps(info))#f.write(pickle.dumps(info)) |
Loads and load differences:
| 123 |
data_from_atm=pickle.load(f)#data_from_atm=pickle.loads(f.read()) |
Pickle (unique in Python, supports all Python data types)
Convert a dictionary to a string
Import picklef= Open ("User_acc.txt", "WB") info={ "Alex": "123", "Jack": "4444"}f.write (Pickle.dumps (info)) F.close ()
Convert a string to a dictionary
Import picklef= Open ("User_acc.txt", "RB") Data_from_atm=pickle.loads (F.read ()) print (DATA_FROM_ATM)
JSON (common to all languages, support dictionaries, lists, tuples)
Convert a dictionary to a string
Import pickleimport jsonf= Open ("User_acc.txt", "W") info={ "Alex": "123", "Jack": "4444"}f.write (Json.dumps ( info)) F.close ()
Convert a string to a dictionary
Import pickle,jsonf= Open ("User_acc.txt", "R") Data_from_atm=json.loads (F.read ()) print (DATA_FROM_ATM)
Instance:
Shelve module of common modules
The shelve module is a simple k,v module that persists memory data through a file and can persist any Python data format that pickle can support
| 123456789101112131415161718 |
importshelve d =shelve.open(‘shelve_test‘) #打开一个文件 classTest(object): def__init__(self,n): self.n =n t =Test(123)t2 = Test(123334) name =["alex","rain","test"]d["test"] =name #持久化列表d["t1"] =t #持久化类d["t2"] =t2 d.close() |
The difference between shelve and pickle is:
Shelve is simpler than the Pickle module, there is only one open function, returns a dictionary-like object, readable and writable, and the other shelve want to repeat dump how many objects can be
XML processing of common modules
XML is a protocol that implements data exchange between different languages or programs, much like JSON, but JSON is simpler to use, but in ancient times, in the Dark Ages when JSON was not yet born, you could only choose to use XML, and so far many traditional companies, such as the financial industry, are mostly XML-like interfaces.
The format of XML is as follows: by the <> node to distinguish the data structure.
<?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 protocols are supported in each language, and in Python you can manipulate XML with the following modules
| 123456789101112131415 |
importxml.etree.ElementTree as ET tree =ET.parse("xmltest.xml")root =tree.getroot()print(root.tag) #遍历xml文档forchild inroot: print(child.tag, child.attrib) fori inchild: print(i.tag,i.text) #只遍历year 节点fornode inroot.iter(‘year‘): print(node.tag,node.text) |
modifying and deleting XML document content
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" ) #删除nodefor Country in Root.findall (' Country '): rank = int (country.find (' rank '). Text) If rank > 50: root.remove (country) tree.write (' Output.xml ')
Create your own XML document
| 12345678910111213141516 |
importxml.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) #打印生成的格式 |
Python Learning notes (vi)