Python---pickle模块

pickle模块可以将任意的对象序列化成二进制的字符串写入到文件中。
还可以从文件中读取并且转为写入时候类型。

pickle.dumps(obj)
功能:将obj进行序列化

pickle.loads(bytestr)
功能:将二进制的字符串转为对象

import pickle
class Card:
    def __init__(self, cardnum, password, money, lock=False):
        self.cardnum = cardnum
        self.password = password
        self.money = money
        self.lock = lock

if __name__ == '__main__':
    card = Card("101110","111",10000)
    card2 = Card("101112","111",10000)
    card3 = Card("101113","111",10000)
    cardlist = [card,card2,card3]

    with open("picdemo.txt","wb") as f:
        f.write(pickle.dumps(cardlist))        #将对象序列化为二进制的字符串写入文件

    with open("picdemo.txt","rb") as f2:
        print(pickle._loads(f2.read()))        #将二进制的字符串反序列化为对象

 

pickle.dump(obj,f)
参数一:被序列化的对象
参数二:打开的文件
功能:将obj序列化并且存入到打开的文件中

pickle.load(f)
功能:将文件中的内容读取并且转为对象

    with open("picdemo2.txt","wb") as f:
        pickle._dump(cardlist,f)

    with open("picdemo2.txt","rb") as f2:
        print(pickle.load(f2))

你可能感兴趣的:(Python---pickle模块)