Python pickle is an essential tool for serializing and de-serializing Python objects, such as lists, dictionaries, and custom objects, offering a seamless method to store and retrieve data with efficiency.
So we can easily store python lists,dictionary and frequently used object which need to be stored.
Pickle is fast is efficient. Evan I have made a super fast efficient CLI dictionary with it and on other projects. I will share the dictionary code later in this post.
Lets dive into an easy example
For using pickle we import pickle, its build in python.
import pickle
my_list=[1,2,3,4,5]
#store in picke file
with open('myList.pickle', 'wb') as f:
pickle.dump(my_list, f)
# Load the data
with open('myList.pickle', 'rb') as f:
my_list = pickle.load(f)
print(my_list)
This is another example with time.
import time
import pickle
t=time.ctime()
old_data=[t]
n=True
try:
with open('datafile.pickle', 'rb') as data:
old_data= pickle.load(data)
try:
old_data.append(t)
except:
old_data=list(old_data)
old_data.append(t)
data.close()
n=True
except:
with open('datafile.pickle', 'wb') as data:
pickle.dump(old_data, data)
data.close()
print(old_data)
n=False
if n==True:
with open('datafile.pickle', 'wb') as data:
pickle.dump(old_data, data)
data.close()
print(old_data)
Test the example code here
If you run this program again again You will notice that Its print the time also adding new time in the list. So its updating and storing the list in the pickle file.
Now Another simple practical project with pickle is the Command Line Interface English dictionary
I am providing the GitHub code link. Try it by yourself. Github Code
You can do wonderful things with pickle. But before going with serious project keep on mind the security issue with pickle