Python: pickle

  

import pickle
from pathlib import Path
file='d:/v/vbn'
p=Path(file)
if not p.parent.exists():
    p.parent.mkdir(parents=True)

with open(str(p),mode='wb') as f:
    s1=99
    s2='vbn'
    s3=['a','b',['c','d']]
    pickle.dump(s1,f)
    pickle.dump(s2,f)
    pickle.dump(s3,f)

with open(str(p),mode='rb') as f:
    ss=[]
    for b in range(3):
        ss.append(pickle.load(f))
    print(ss,type(ss[0]))

import pickle

class BB:
    bbb='vbn'
    def show(self):
        print('show')

bb=BB()

sr=pickle.dumps(bb)
print('sr={}'.format(sr))

b2=pickle.loads(sr)
print(b2)
print(b2.bbb)
b2.show()

 

from pathlib import Path
import pickle

path='c:/v/b'

p=Path(path)
if not p.parent.exists():
    p.parent.mkdir(parents=True)

lst='a b c e'.split()
d=dict(zip('abc',range(3)))

class BB():
    mmm='bbbbbbb'
    def __init__(self):
        self.vvv='ppppppp'
    def show(self):
        print('vbn')
        a='bbbbbbbbbbbbbbbbbbbbbbbbb'
        print(a)

bb=BB()
print(bb)

with open(path,'wb+') as f:
    # pickle.dump(lst,f)
    # pickle.dump(d,f)
    # pickle.dump(BB,f)
    pickle.dump(bb,f)

with open(path,'rb+') as f:
    # print(pickle.load(f))
    # print(pickle.load(f))
    tmp=pickle.load(f)
    print(tmp,type(tmp))
    tmp.show()

 

import pickle, io


class Exposition:
    def __init__(self, name):
        self.name = name
        l = list(name)
        l.reverse()
        self.name_backwards = ''.join(l)


data = []
data.append(Exposition('pickle'))
data.append(Exposition('exposition'))
sio = io.BytesIO()

for o in data:
    print(o.name, o.name_backwards)
    pickle.dump(o, sio)
    sio.flush()

sio.seek(0, 0)
print(sio.read())

sio.seek(0, 0)
while True:
    try:
        o = pickle.load(sio)
    except EOFError:
        break
    else:
        print(o.name, o.name_backwards)

 

posted @ 2020-09-19 20:47  ascertain  阅读(120)  评论(0编辑  收藏  举报