Scene
Example 1dic=Str ({' Age':' -'})f= Open ('text','W') F.write (DIC) F.close () Example 2f= Open ('text','R') Data=F.read ()Print(Eval (Data) [' Age'])
When we store the memory data object in a file, it is impossible to store the Dictionary object directly, it must be converted to the string format str (), when we read the dictionary format object stored in the file through the F.read () method, the reading is also a string that must be converted with the Eval () method, which is very Lou.
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
JSON module
In the above scenario, the better approach is through the JSON module, because JSON represents a string that can be read by all languages, easily stored to disk, or transmitted over a network. JSON is not only a standard format, but also faster than XML, and can be read directly in the Web page, very convenient.
ImportJsondic= {' Age':' -'}#Write Filedata =Json.dumps (DIC) F= Open ('text','W') f.write (data) f.close ()#Read Filef = open ('text','R') Data=f.read () content=json.loads (data)Print(content[' Age'])
Pickle Module
The problem with Pickle is the same as for all other programming language-specific serialization problems, that is, it can only be used in Python, and may be incompatible with each other in Python, so it's okay to save only those unimportant data with pickle and not successfully deserialize it.
ImportPickledeffoo ():Print('OK')#Write Filedata =pickle.dumps (foo) F= Open ('text','WB') f.write (data) f.close ()#Read Filef = open ('text','RB') Data=f.read () content=pickle.loads (data) content ()#Can ' t get attribute ' foo ' on <module ' __main__ ' from ' C:/users/lg/pycharmprojects/mystuff/march/day23/json_ module.py ' >
- Note: The write mode must be WB, RB
- Reading a file is an error because the function memory address cannot be found, so if you want to read it, the function must be in memory address.
Dump & Load Method
1. Dump
Import= {'age':'+ ' = open (' text','w') json.dump (dic,f) f.close ()
- The process by which dump will be converted and written
2. Load
Import= open ('text','r'= Json.load (f)print(data['age') f.close ()
- The process by which load will be converted and read
Python basic syntax-JSON & Pickle