簡體   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