zoukankan      html  css  js  c++  java
  • day⑥:shelve模块

    shelve 模块

    shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

    说白了,就是pickle的高级吧


    例子:

    一.pickle 处理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']


    二.shelve 处理python的数据格式
    ①shelve之持久化.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()


    ②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







  • 相关阅读:
    【模拟】HDU 5752 Sqrt Bo
    【数学】HDU 5753 Permutation Bo
    【模拟】Codeforces 706A Beru-taxi
    【二分】Codeforces 706B Interesting drink
    【动态规划】Codeforces 706C Hard problem
    【字典树】【贪心】Codeforces 706D Vasiliy's Multiset
    【中国剩余定理】POJ 1006 & HDU 1370 Biorhythms
    计算机存储单位
    转载_Linux下查看文件和文件夹大小
    反问题_不适定_正则化
  • 原文地址:https://www.cnblogs.com/binhy0428/p/5221242.html
Copyright © 2011-2022 走看看