pickle使用方法

1、多次存储和提取

import pickle

class Cat:
    '''
    The object of cat
    '''
    head = "head"
    body = "body"
    foot = "foot"

    #  initial the cat
    def __init__(self, head='0', body='1', foot='2'):
        self.head = head
        self.body = body
        self.foot = foot


if __name__ == '__main__':

    file_path = 'D:/tmp.pk'

    # Save objects
    write_file = open(file_path, 'wb')

    # The number of 'dump' must be equal the number of 'load'
    pickle.dump(Cat(1, 2, 3), write_file)
    pickle.dump(Cat(4, 5, 6), write_file)
    write_file.close()

    read_file = open(file_path, 'rb')
    cat = pickle.load(read_file)
    print(str(cat.head) + " " + str(cat.body) + " " + str(cat.foot))
    cat = pickle.load(read_file)
    print(str(cat.head) + " " + str(cat.body) + " " + str(cat.foot))
    read_file.close()

2、列表存取

import pickle


class Cat:
    '''
    The object of cat
    '''
    head = "head"
    body = "body"
    foot = "foot"

    #  initial the cat
    def __init__(self, head='0', body='1', foot='2'):
        self.head = head
        self.body = body
        self.foot = foot


def open_pickle_file(file_path):
    '''
    Open the file of bin
    :param file_path: path of file
    :return:
    '''
    with open(file_path, 'rb') as f:
        data = pickle.load(f)
        return data
    return 0


def save_pickle_file(data, file_path):
    '''
    Save the file of data
    :param data: The data of input
    :param file_path: The path of file
    :return:
    '''
    with open(file_path, 'wb') as f:
        pickle.dump(data, f)
    return 0


if __name__ == '__main__':
    file_path = 'D:/tmp.pk'

    data = list()
    data.append(Cat(1, 2, 3))
    data.append(Cat(4, 5, 6))

    # Save list
    save_pickle_file(data, file_path)
    cats = open_pickle_file(file_path)
    print(str(cats[0].head)+" "+str(cats[0].body)+" "+str(cats[0].foot))
    print(str(cats[1].head) + " " + str(cats[1].body) + " " + str(cats[1].foot))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值