SYS module
- SYS module is an interface that interacts with the Python interpreter
sys.argv command line argument list, the first element is the program itself path Sys.exit (n) exits the program, exit normally exits (0), error exits Sys.exit (1) sys.version Gets the version information of the Python interpreter Sys.path returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing Sys.platform returns the operating system platform name
Serialization Module
- purpose of serialization :
- Persist custom objects in some form of storage
- Passing objects from one place to another
- Make the program more maintainable
#The JSON module provides four functions: dumps, dump, loads, loadImportJsondic= {'K1':'v1','K2':'v2','K3':'v3'}str_dic= Json.dumps (DIC)#Serialization: Converting a dictionary into a stringPrint(Type (str_dic), str_dic)#<class ' str ' > {"K3": "V3", "K1": "V1", "K2": "V2"}#Note that the string in the dictionary of the string type converted by JSON is represented by ""Dic2= Json.loads (Str_dic)#deserialization: Converts a dictionary of a string format into a dictionary#Note that the string in the dictionary of string types to be processed with the JSON loads function must be represented by ""Print(Type (DIC2), Dic2)#<class ' dict ' > {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}List_dic= [1,['a','b','C'],3,{'K1':'v1','K2':'v2'}]str_dic= Json.dumps (List_dic)#you can also handle nested data typesPrint(Type (str_dic), str_dic)#<class ' str ' > [1, ["A", "B", "C"], 3, {"K1": "V1", "K2": "V2"}]List_dic2 =json.loads (str_dic)Print(Type (LIST_DIC2), List_dic2)#<class ' list ' > [1, [' A ', ' B ', ' C '], 3, {' K1 ': ' v1 ', ' K2 ': ' V2 '}]
Importjsonf= Open ('Json_file','W') DiC= {'K1':'v1','K2':'v2','K3':'v3'}json.dump (dic,f)#The dump method receives a file handle and translates the dictionary directly into a JSON string to write to the fileF.close () F= Open ('Json_file') Dic2= Json.load (f)#The load method receives a file handle, directly converting the JSON string in the file into a data structure to returnf.close ()Print(Type (DIC2), Dic2)
Importjsonf= Open ('file','W') Json.dump ({'Nationality':'China'},f) ret= Json.dumps ({'Nationality':'China'}) f.write (ret+'\ n') Json.dump ({'Nationality':'United States'},f,ensure_ascii=False) ret= Json.dumps ({'Nationality':'United States'},ensure_ascii=False) f.write (ret+'\ n') F.close ()ensure_ascii keyword Parameters
- Pickle
- JSON & Pickle
-
- JSON, used to convert between string and Python data types
- Pickle for conversion between Python-specific types and Python data types
#The Pickle module provides four functions: dumps, dump (serialize, save), loads (deserialization, read), load (not only serializable dictionary, list ... Can serialize arbitrary data types in PythonImportPickledic= {'K1':'v1','K2':'v2','K3':'v3'}str_dic=pickle.dumps (DIC)Print(Str_dic)#A string of binary contentDic2=pickle.loads (str_dic)Print(DIC2)#DictionaryImportTimestruct_time= Time.localtime (1000000000)Print(struct_time) F= Open ('Pickle_file','WB') Pickle.dump (struct_time,f) f.close () F= Open ('Pickle_file','RB') struct_time2=pickle.load (f)Print(struct_time2.tm_year)
# Shelve is also a serialization tool that Python provides to us, which is simpler than pickle. # shelve only gives us an open method, which is accessed using key and is similar to a dictionary. ImportSHELVEF= Shelve.open ('Shelve_file') f['Key'] = {'int': 10,'float': 9.5,'string':'Sample Data'}#directly to the file handle, you can deposit dataf.close ()ImportSHELVEF1= Shelve.open ('Shelve_file') Existing= f1['Key']#when you take out the data, you just need to get it directly with key, but if key doesn't exist, it will be an error.f1.close ()Print(existing)
# This module has a limit, it does not support multiple applications at the same time to the same DB write operations. So when we know that our application is only read, we can let shelve open dbimport= Shelve.open ('shelve_file ', flag='r'= f['key'] F.close ()print(existing)
#since shelve does not record any modifications to the persisted object by default, we need to modify the default parameters at Shelve.open () or the object's modifications will not be saved. ImportSHELVEF1= Shelve.open ('Shelve_file')Print(f1['Key']) f1['Key']['New_value'] ='This is not here before'f1.close () F2= Shelve.open ('Shelve_file', writeback=True)Print(f2['Key']) f2['Key']['New_value'] ='This is not here before'f2.close ()"""There are pros and cons to the writeback approach. The advantage is to reduce the probability of our error, and to make the object's persistence more transparent to the user, but this method is not required in all cases, first, after using writeback, shelf in open () will increase the additional memory consumption, and when the DB in close () , each object in the cache is written to the DB, which also brings additional wait times. Because shelve has no way of knowing which objects in the cache have been modified and which objects have not been modified, all objects will be written. """
The SYS module and the serialization module of the Python module