Day⑥:shelve Module

Source: Internet
Author: User

Shelve module

The shelve module is a simple k,v module that persists memory data through a file and can persist any Python data format that pickle can support

Frankly, it's Pickle's senior.


Example:

I. Pickle processing data formats for Python

①pickle_dump.py

  
 
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. #这个例子是pickle dump对比shelve之持久化
  4. import pickle
  5. class Test(object):
  6. def __init__(self,n):
  7. self.n=n
  8. t=Test(123)
  9. t2=Test(456)
  10. name=["yaobin","test","haha"]
  11. f=open("pickle_test.pk1",‘wb‘)
  12. pickle.dump(t,f) #把t类dump进去
  13. pickle.dump(t2,f) #把t2类dump进去
  14. pickle.dump(name,f) #把列表也dump进去
  15. f.close()


②pickle_load.py
  
 
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. #这个例子主要pickle load对比shelve之取值
  4. import pickle
  5. f=open("pickle_test.pk1","rb")
  6. #pickle的load 是先dump进去的,先出来,先进先出
  7. #第一次load
  8. a=pickle.load(f)
  9. print(a.n)
  10. #第二次load
  11. b=pickle.load(f)
  12. print(b.n)
  13. #第三次load
  14. c=pickle.load(f)
  15. print(c)
  16. #总结: 不能随时的load我想要的东西出来啊,所以才有shelve,可以使用key的方式持久化,再通过key取出来。
  17. #结果
  18. 123
  19. 456
  20. [‘yaobin‘, ‘test‘, ‘haha‘]


two. Shelve processing python's data format①shelve the persistence of the. py
  
 
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import shelve
  4. d = shelve.open(‘shelve_test‘) #打开一个文件
  5. class Test(object):
  6. def __init__(self,n):
  7. self.n = n
  8. t1 = Test(123) #实例化
  9. t2 = Test(456) #实例化
  10. name = ["alex","rain","test"] #列表
  11. d["list"] = name #持久化列表
  12. d["t1"] = t1 #持久化类
  13. d["t2"] = t2 #持久化类
  14. d.close()


Value of ②shelve. py
  
 
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import shelve
  4. a=shelve.open(‘shelve_test‘) #打开一个文件
  5. #用shelve的get方法取出key对应的值,比pickle load 要好
  6. h1=a.get("list")
  7. h2=a.get("t1")
  8. h3=a.get("t2")
  9. print(h1)
  10. print(h2.n)
  11. print(h3.n)
  12. #结果
  13. [‘alex‘, ‘rain‘, ‘test‘]
  14. 123
  15. 456





From for notes (Wiz)

Day⑥:shelve Module

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.