问题 是我只能读取 InputFile.bak 文件的第一行。我如何使用 cPickle 从文件中读取所有信息。
输入文件-InputFile.bak
(dp1
S'Here we go'
p2
(cdatetime
date
p3
(S'\x07\xdc\x0c\x0c'
tRp4
cdatetime
time
p5
(S'\x0c\x0c\x00\x00\x00\x00'
tRp6
tp7
s.(dp1
S'Here we go'
p2
(cdatetime
date
p3
(S'\x07\xdc\x0c\x0c'
tRp4
cdatetime
time
p5
(S'\x0c\x0c\x00\x00\x00\x00'
tRp6
tp7
s.(dp1
S'Here we go'
p2
(cdatetime
date
p3
(S'\x07\xdc\x0c\x0c'
tRp4
cdatetime
time
p5
(S'\x0c\x0c\x00\x00\x00\x00'
tRp6
tp7
sS'Google Searching'
p8
(g3
(S'\x07\xdc\x0c\x0b'
tRp9
g5
(S'\x01\x17\x00\x00\x00\x00'
tRp10
tp11
s.
源代码
import time
import datetime
import cPickle
import os
from sys import exit
def read_file():
if os.path.exists('InputFile.bak'):
try:
fname = open('InputFile.bak', 'rb')
file_src = cPickle.Unpickler(fname)
item_name = file_src.load()
for k, v in item_name.iteritems():
print v[0], "\t", v[1],"\t", k
finally:
fname.close()
else:
item_name = {}
if __name__ == '__main__':
read_file()
非常感谢。
请您参考如下方法:
您可以使用loop 来获取所有记录。
def read_file():
if os.path.exists('InputFile.bak'):
# try:
with open('InputFile.bak', 'rb') as fname:
while True:
try:
item_name = cPickle.load(fname)
for k, v in item_name.iteritems():
print v[0], "\t", v[1],"\t", k
except EOFError:
break
else:
item_name = {}
if __name__ == '__main__':
read_file()
