python序列化的原理和作用_Python pickle类库介绍(对象序列化和反序列化)

class textreader:

"""print and number lines in a text file."""

def __init__(self, filename):

self.filename = filename

self.file = open(filename)

self.lineno = 0

def readline(self):

self.lineno += 1

line = self.file.readline()

if not line:

return none

if line.endswith('\n'):

line = line[:-1]

return "%i: %s" % (self.lineno, line)

def __getstate__(self):

# copy the object's state from self.__dict__ which contains

# all our instance attributes. always use the dict.copy()

# method to avoid modifying the original state.

state = self.__dict__.copy()

# remove the unpicklable entries.

del state['file']

return state

def __setstate__(self, state):

# restore instance attributes (i.e., filename and lineno).

self.__dict__.update(state)

# restore the previously opened file's state. to do so, we need to

# reopen it and read from it until the line count is restored.

file = open(self.filename)

for _ in range(self.lineno):

file.readline()

# finally, save the file.

self.file = file

reader = textreader("hello.txt")

print(reader.readline())

print(reader.readline())

s = pickle.dumps(reader)

#print(s)

new_reader = pickle.loads(s)

print(new_reader.readline())

# the output is

# 1: hello

# 2: how are you

# 3: goodbye

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值