"Python Tour" chapter III (II): Pickle serialization

Source: Internet
Author: User

Description: Description of Pickle

Make the following statement:

The concept of serialization is simple. There is a data structure in memory that you want to save, reuse, or send to others. What would you do? Well, it depends on how you want to save it, how to reuse it, and who to send it to. Many games allow you to save your progress when you exit, and then go back to where you left off when you started again. (In fact, many non-gaming programs do the same thing.) In this case, a data structure that captures the current progress needs to be saved to disk when you exit, and then loaded from disk when you reboot. What can be stored with the Pickle module? – All Python-supported native types: Boolean, Integer, floating-point, plural, string, bytes (byte string) object, byte array, and none.– a list of any native types, tuples, dictionaries – a list of any native types, meta A group, a dictionary, and a collection of lists, tuples, dictionaries, and collections (which can be nested until Python supports the maximum number of recursive layers). – Instances of functions, classes, and classes (with warnings).



Simple introduction and use of 1.Pickle


• A brief description of the following:

A. The data structure of the dictionary is stored in memory, saved as a file is not recognized, if you want to save, and in the next open can also be used, need to do pickle serialization storage;

B. Need to deserialize when reading;

C.pickle can save the progress of the execution of the program;


• Give instance 1:pickle save only one State

A. Storage serialization

#!/usr/bin/env Pythonimport pickleaccount_info = {' 8906143632 ': [' alex3714 ', 15000, 15000], ' 8908223631 ': [' Rachel ', 9000,9000]}f=file (' account.pkl ', ' WB ') pickle.dump (account_info,f) f.close ()

B. Read serialization

#!/usr/bin/env pythonimport picklepkl_file = file (' account.pkl ', ' RB ') Account_list = Pickle.load (pkl_file) Pkl_ File.close () Print account_list

C. The results of the implementation are as follows:

[Email protected]:/mnt/hgfs/python/day3$ python pickle_w.py [email protected]:/mnt/hgfs/python/day3$ python pickle_ r.py {' 8908223631 ': [' Rachel ', 9000, 9000], ' 8906143632 ': [' alex3714 ', 15000, 15000]}

D. The status of the dictionary is saved in the generated ACCOUNT.PKL:

[Email protected]:/mnt/hgfs/python/day3$ cat account.pkl (dp0s ' 8908223631 ' p1 (lp2s ' Rachel ' P3ai9000ai9000ass ') 8906143632 ' P4 (lp5s ' alex3714 ' p6ai15000ai15000as.


• Instance 2:pickle save multiple states

A. The storage serialization code is modified to read as follows:

#!/usr/bin/env Pythonimport pickleaccount_info = {' 8906143632 ': [' alex3714 ', 15000, 15000], ' 8908223631 ': [' Rachel ',    9000,9000]}f=file (' account.pkl ', ' WB ') pickle.dump (account_info,f) #第一次状态保存account_info [' 8908223631 '][0] = ' xpleaf ' #修改字典中的某项内容pickle. Dump (account_info,f) #第二次状态保存f. Close ()

B. Execute the storage serializer to save two states to the file:

[Email protected]:/mnt/hgfs/python/day3$ Python pickle_w.py [email protected]:/mnt/hgfs/python/day3$ cat Account.pkl ( dp0s ' 8908223631 ' p1 (lp2s ' Rachel ' P3ai9000ai9000ass ' 8906143632 ' P4 (lp5s ' alex3714 ' p6ai15000ai15000as. ( dp0s ' 8908223631 ' p1 (lp2s ' xpleaf ' #对比只保存一次状态的情况, here are more modified content ' xpleaf ' p3ai9000ai9000ass ' 8906143632 ' P4 (lp5s ' alex3714 ') P6ai15000ai15000as.

C. Test in the interactive device:

>>> import pickle>>> f = file (' account.pkl ') >>> acc1  = pickle.load (f)      #反序列化读取第一次状态的内容 >>> acc2 =  Pickle.load (f)      #反序列化读取第二次状态的内容 >>> acc3 = pickle.load (f)       #无第三次状态内容, read failure traceback  (most recent call last):  file  " <stdin> ", line 1, in <module>  file "/usr/lib/python2.7/ Pickle.py ",  line 1378, in load    return unpickler (file). Load ()   File  "/usr/lib/python2.7/pickle.py", line 858, in load     dispatch[key] (self)   File  "/usr/lib/python2.7/pickle.py",  line 880, in  load_eof    raise eoferroreoferror>>> acc1{' 8908223631 ':  [' Rachel ', 9000, 9000],  '8906143632 ':  [' alex3714 ',  15000, 15000]}>>> acc2{' 8908223631 ':  [' xpleaf ',  9000, 9000],  ' 8906143632 ':  [' alex3714 ',  15000, 15000]}

• Multiple states (dump) can be saved in one file, but it is not recommended to have one-to-one state (load);



Other instructions and use of 2.Pickle


• Serialization allows the reading of interactive data between different programs;

· Dump () in Pickle can only store the serialization of the data structure on disk, then load () and then deserialize the associated file of the calling disk;

• Use Pickle's dumps () and loads () to operate directly in memory:

>>> acc1{' 8908223631 ': [' Rachel ', 9000, 9000], ' 8906143632 ': [' alex3714 ', 15000, 15000]}>>> Pickle.dumps (ACC1) "(Dp0\ns ' 8908223631 ' \np1\n (lp2\ns ' Rachel ' \np3\nai9000\nai9000\nass ' 8906143632 ' \np4\n (Lp5\nS ') alex3714 ' \np6\nai15000\nai15000\nas. " >>> C = pickle.dumps (ACC1) >>> pickle.loads (c) {' 8908223631 ': [' Rachel ', 9000, 9000], ' 8906143632 ': [' alex3714 ', 15000, 15000]}

• The state of the dynamic interactive program can be realized by simply providing the operation interface (example of game progress Switch, P1--P2,P1 the game progress to P2 in real time);

• JSON is just as important as pickle, and usage is similar to pickle;

• The idea of serialization plays an important role in the interaction of data structures between different platforms and different programming languages, and is not described here because it has not been studied in depth.





This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1697298

"Python Tour" chapter III (II): Pickle serialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.