Import Shelveimport datetimed = Shelve.open (' shelve_test ') ' Write file ' ' info = {' age ': ' ' job ': ' IT '}name = [' Jack ', ' Rose '] d[' name '] = named[' info '] = infod[' data '] = Datetime.datetime.now () d.close () ' Read file ' d = shelve.open (' shelve_test ') Print (D.get (' name ')) print (D.get (' info ')) print (D.get (' Date ')) D.close ()
As you can see, the shelve module and JSON work well for the file, but there are three files when you save the file,
Do not care about the format of these three files, normal read and write on the line.
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:
Here are some examples to learn:
First, let's look at the JSON dumps and loads methods.
1 2 3 4 5 6 |
s1 = { "k1" : "v1" } st = json.dumps(s1) print (st, type (st)) s = ‘{"k1":"v1"}‘ dic = json.loads(s) print (dic, type (dic)) |
The output is:
1 2 |
{ " K1 " : "v1" } < class ' str ' > { ' K1 ' : ' v1 ' < class ' dict ' > |
You can see that the JSON dumps method converts the data to a character type when the data is processed, and loads restores its type again.
Then look at the dump and load methods of JSON, with examples to understand:
1 2 3 4 |
li = [ 11 , 22 , 33 ] li = json.dump(li, open ( ‘db‘ , ‘w‘ )) li = json.load( open ( ‘db‘ , ‘r‘ )) print (li, type (li)) |
The difference between JSON modules dumps, loads, load, dump:
Load,dump can load external files, process file data, dumps,loads mainly handle in-memory data
Pickle module:
Let's take a look at Pickle's dumps and loads methods, which we'll look at by example:
1 2 3 4 5 6 |
import pickle i = [ 11 , 22 , 33 ] r = pickle.dumps(li) print (r) result = pickle.loads(r) print (result) |
The result is:
1 2 |
b ‘\x80\x03]q\x00(K\x0bK\x16K!e.‘ [ 11 , 22 , 33 ] |
The Pickle Dupms method saves the data as a pickle-specific data type
Looking at the dump and load methods of pickle, let's take a look at the example:
1 2 3 4 5 |
import pickle i = [ 11 , 22 , 33 ] pickle.dump(i, open ( ‘db‘ , ‘wb‘ )) result = pickle.load( open ( ‘db‘ , ‘rb‘ )) print (result) |
It is important to note that the dump file or the load file is required to use the binary.
Python shelve module