Python Common module Two
Shelve
Pickle
Json
Shelve module
import shelvedef fun1(): pass= shelve.open(‘test_shelve‘)s[‘dic‘= {}.fromkeys(list(‘abcdefg‘0)s[‘func‘= fun1s[‘list‘=list(range(10))s.close()
= shelve.open(‘test_shelve‘= shelve.open(‘test_shelve‘= s.get(‘dic‘= s.get(‘func‘= s.get(‘list‘)
Pickle Module
import=open(‘save.pkl‘‘wb‘, encoding=‘utf8‘= {}.fromkeys(list(‘qwertasd‘1)pickle.dump(dic, f)f.close()
import=open(‘save.pkl‘‘rb‘= pickle.load(f)printtype(data))
JSON module
= [‘我‘‘你‘‘它‘‘asdas‘=open(‘save.json‘‘w‘)json.dump(s, f)f.close()
- Code Listing 2: Using JSON modules to read JSON-formatted content
=open(‘save.json‘‘r‘, encoding=‘utf8‘= json.load(f1)# result = json.loads(f1.read())
- Serializes the string JSON into a file that is encoded in Unicode format
= json.dumps(s)printtype(data))# ["\u6211", "\u4f60", "\u5b83"] <class ‘str‘>=# 直接反序列json序列化数据print(result)# [‘我‘, ‘你‘, ‘它‘]
JSON, Pickle, shelve three differences
The main differences are several points:
- The pickle and shelve modules support all Python data types, including functions, but JSON only supports data types such as Dic/list/tuple/str/int;
- Pikle and shelve can only be used in Python, but JSON is cross-lingual;
The role of JSON, Pickle, shelve three modules
- For converting between strings and python or other programming language data types, not only can you save data to your hard disk, but you can also save its data type
Python Common Modules 2