Python3 Python對象持久化(pickle / shelve)

本文由 Luzhuo 編寫,轉發請保留該信息. 
原文: http://blog.csdn.net/rozol/article/details/71081854


以下代碼以Python3.6.1爲例 
Less is more!


pickle

#coding=utf-8
# pickledemo.py Pickle
# 用於對Python對象進行序列化和反序列化的二進制協議

import pickle

def demo():
    # --- 序列化 ---
    f = open("pickle.txt", "wb+")
    lists = [123, "中文", [456]]
    strs = "字符串"
    num = 123

    # 寫入
    pickle.dump(lists, f) # 序列化到文件
    pickle.dump(strs, f)
    pickle.dump(num, f)

    # 關閉
    f.close()


    # --- 反序列化 ---
    f = open("pickle.txt", "rb+")

    # 讀取
    data = pickle.load(f) # 從文件反序列化
    print (data)
    data = pickle.load(f)
    print(data)
    data = pickle.load(f)
    print(data)

    f.close()


def pickle_funs():
    lists = [123, "中文", [456]]
    f = open("pickle.txt", "wb+") # (注:wb+二進制讀寫)

    num = pickle.HIGHEST_PROTOCOL # 目前最高的酸洗協議(4)
    num = pickle.DEFAULT_PROTOCOL # 默認的酸洗協議(3) {3:明確支持bytes對象; 4:更多種類的對象和數據格式優化的支持}

    # --- 序列化 ---
    # dump(obj, file, protocol=None, *, fix_imports=True) // 將obj寫入文件
    pickle.dump(lists, f)
    # dumps(obj, protocol=None, *, fix_imports=True) // 將obj寫入bytes
    bytes = pickle.dumps(lists)

    # --- 反序列化 ---
    # load(file, *, fix_imports=True, encoding="ASCII", errors="strict") // 從file讀取obj對象
    lists = pickle.load(f)
    # loads(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict") // 從bytes讀取obj對象
    lists = pickle.loads(bytes)

    # --- 異常 ---
    try:
        pass
    except pickle.PicklingError: # 序列化時異常
        pass
    except pickle.UnpicklingError: # 反序列化時異常
        pass
    except pickle.PickleError: # pickling異常的公共基類
        pass



if __name__ == "__main__":
    demo()
    pickle_funs()

shelve


#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/26'
# shelve_demo.py 持久性字典:Python對象的持久化
# 鍵值對形式, 將內存數據通過文件持久化, 值支持任何pickle支持的Python數據格式
# 與pickle的主要區別是鍵值對方式, 並且在目錄下生成三個文件

import shelve


class Person(object):
    def __init__(self):
        self.name = "luzhuo"
        self.age = 21

    def __str__(self):
        return "name: {}, age: {}".format(self.name, self.age)

path = "file.txt"


def shelve_write():
    '''
    序列化
    '''

    with shelve.open(path) as write: # 打開
        write["nums"] = [1, 2, 3, 4, 5]  # 寫
        write["obj"] = Person()


def shelve_read():
    '''
    反序列化
    '''

    with shelve.open(path) as read:  # 打開
        nums = read.get("nums")  # 讀取
        print(nums)
        clazz = read["obj"]
        print(clazz)

        del read["obj"]  # 刪除
        print("obj" in read)

        keys = list(read.keys())  # 所有key
        print(keys)


def shelve_func():
    # 打開, filename:文件名, writeback:是否回寫(True回寫,耗內存), 返回Shelf對象
    # shelve.open(filename, flag='c', protocol=None, writeback=False)
    d = shelve.open(path)

    # Shelf
    # 支持字典支持的所有方法
    # get(self, key, default=None) // 獲取 == data = shelf["key"]
    data = d.get("key")
    d.sync()  # 同步(清空緩存,同步磁盤)
    d.close()  # 同步並關閉


    # class shelve.Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8')
    # class shelve.BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8') // Shelf的子類
    # class shelve.DbfilenameShelf(filename, flag='c', protocol=None, writeback=False) // Shelf的子類


if __name__ == "__main__":
    shelve_write()
    shelve_read()

    # shelve_func()








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章