繁体   English   中英

使用 Python cPickle 从文件中读取数据

[英]Reading data from file using Python cPickle

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

如果您在阅读文件时知道另一个进程不会添加到文件中,您可以根据文件大小检查当前进度:

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 = {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM