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?
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.
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 .
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With