Usage of Python pickle and shelve modules

Source: Internet
Author: User
1.pickle

Write: Open a file descriptor in write mode, call Pickle.dump to write the object in
Copy the Code code as follows:


DN = {' Baidu ': ' www.baidu.com ', ' qq ': ' www.qq.com ', ' a ': ' www.360.cn '}

name = [' Mayun ', ' Mahuateng ', ' Liyanhong ']

f = open (R ' C:\a.txt ', ' W ')

Pickle.dump (dn,f) # #写一个对象

Pickle.dump (name,f) # #再写一个对象

F.close ()

READ: Open file descriptor as read, call Pickle.load Load Object

f = open (R ' C:\a.txt ')

Pickle.load (f) # #加载一个对象

Pickle.load (f) # #加载另一个对象

F.close ()


2.shelve

The shelve module is simpler than the Pickle module, with only one open function, which returns a dictionary-like object, readable and writable
Copy the Code code as follows:


F = Shelve.open (R ' C:\b.txt ')

F # #返回空字典

f[' baidu '] = ' www.baidu.com '

f[' qq '] = ' www.qq.com '

f[' www.360.cn ') = '

F # #返回字典

F.close ()

F = Shelve.open (R ' C:\b.txt ')

F # #返回字典f

  • 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.