How to search a pickle file in Python?
Prerequisites: pickle file
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Pickle serializes a single object at a time, and reads back a single object — the pickled data is recorded in sequence on the file.
If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you’ve written).
After de-serializing the first object, the file-pointer is at the beginning of the next object — if you simply call pickle.load again, it will read that next object — do that until the end of the file.
- dump()– used to write a pickled representation of obj to the open file object file.
pickle.dump(obj, file, protocol = None, *, fix_imports = True)
- load()– used to read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified.
pickle.load(file, *, fix_imports = True, encoding = “ASCII”, errors = “strict”)
- seek(0)- Pickle records can be concatenated into a file, so yes, you can just pickle.load(f) multiple times, but the files themselves are not indexed in a way that would let you seek into a given record. What your f.seek(0) is doing is seeking into the third byte in the file, which is in the middle of a pickle record, and thus is unpicklable. If you need random access, you might want to look into the built-in shelve module which builds a dictionary-like interface on top of pickle using a database file module.
- truncate()- changes the file size
Given below is the implantation for adding to a pickle file.
After the pickle file is created and loaded with data successfully, searching can be performed.
- Import module
- Open pickle file
- Take some element to base search upon
- Display result if found