使用Python cPickle读取文件数据

2 投票
2 回答
1522 浏览
提问于 2025-04-18 03:13

问题是我只能读取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()

非常感谢。

2 个回答

1

如果你知道在你读取文件的时候,其他程序不会往这个文件里添加内容,那么你可以通过文件的大小来检查你当前的读取进度:

def read_file():
    fname = 'InputFile.bak'
    if os.path.exists(fname):
        fsize = os.path.getsize(fname)
        with open(fname, 'rb') as fh:
            while fh.tell() < fsize:
                item = cPickle.load(fh)
                for k, v in item.iteritems():
                    print v[0], "\t", v[1],"\t", k
    else:
        item_name = {}
1

你可以用 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()

撰写回答