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