Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load data from Python pickle file in a loop?

Tags:

python

pickle

In a small data-acquisition project we use the Python's pickle to store recorded data, i.e. for each "event" we add it to the output file f with

pkl.dump(event, f, pkl.HIGHEST_PROTOCOL)

where import cPickle as pkl.

In the analysis of the data we read each event, but in contrast to a normal file where processing can be one in a rather elegant way:

with open(filename) as f:
    for line in f:
        do_something()

looping over all the data in a pickle file this becomes a bit more awkward:

with open(filename) as f:
    try:
        while True:
            event = pkl.load(f)
            do_something()
    except (EOFError, UnpicklingError):
        pass

Is it possible to make pickle reading more like the example for regular files above?

like image 874
Darko Veberic Avatar asked Sep 07 '13 17:09

Darko Veberic


People also ask

How do I load pickled data in Python?

Python Pickle load To retrieve pickled data, the steps are quite simple. You have to use pickle. load() function to do that. The primary argument of pickle load function is the file object that you get by opening the file in read-binary (rb) mode.

How do you load objects from pickles?

load() to load an object from a file. Call open(file, "rb") with the filename of the stored Pickle object as file to open the Pickle file for reading in binary. Use pickle. load(file) to load the object from file .

What is pickle dump ()?

The dump() method of the pickle module in Python, converts a Python object hierarchy into a byte stream. This process is also called as serilaization. The converted byte stream can be written to a buffer or to a disk file.

How do you use pickle dumps?

First, import pickle to use it, then we define an example dictionary, which is a Python object. Next, we open a file (note that we open to write bytes in Python 3+), then we use pickle. dump() to put the dict into opened file, then close. Use pickle.


1 Answers

Yes, indeed. Use this generator below to make the events readable in a loop:

def pickleLoader(pklFile):
    try:
        while True:
            yield pkl.load(pklFile)
    except EOFError:
        pass

Now you can simply write:

with open(filename) as f:
    for event in pickleLoader(f):
        do_something()
like image 72
Darko Veberic Avatar answered Oct 15 '22 19:10

Darko Veberic