How to use pickle with python
Recently learn how to use find pickle module for python and decided to document it down for my future references purposes. Heads up, amature python coder here so if there’s something that I describe and my understanding is wrong feel free to point it out.
What is pickle
Pickle is being used to serializing and de-serializing certain object from python. In short, it saves an object from python as physical files on disk. It could be anything from dict to list or even a single string. The saved file could be read during another instance without losing the data.
The two main pickle method that we usually use are dump (save the object into files) and load (read the files). Now let’s move on to how do we use the method.
# -*- coding: utf-8 -*- import pickle import os log_path = r"your_log_path" def write_pickle(data, file_path): with open(file_path, 'wb') as fobj: pickle.dump(data, fobj) def run(): print("test") write_pickle(run(), log_path)
A dump, as the name suggested dumps all the information into a file. We will import pickle module and other nessary module like os module for opening the files to be written on. The files will be opened as an object and pickle will just dump into the object itself.
# -*- coding: utf-8 -*- import pickle import os log_path = r"your_log_path" def read_pickle(file_path): with open(file_path, 'rb') as fobj: return pickle.load(fobj) read_pickle(log_path)
Last but not least, the read method. It’s being used to read the files. You can just return the function so you can actually get the result from running the method.
There are a couple reason why pickle is being widely used and according to the website here, they are these.
- Saving program state to disk.
- Sending python data over TCP connection (for those who wish to send data over network).
- Store python object in a database.
- Cache purposes.
That’s all for now.