Today we learned how to make Python βrememberβ data even after the program closes β using pickle (serialization).
Pickle is a built-in Python module used for serialization:
'wb' mean?pickle.dump() do?try/except?'rb' mean?Pickle is perfect for learning + offline storage. But do not use pickle files from unknown sources β it can be unsafe.
pickleutilities.pyThis file contains two helper functions: saveFile and readFile.
import pickle
def saveFile(filename, data):
# 'wb' = write binary
with open(filename, 'wb') as file:
pickle.dump(data, file)
def readFile(filename):
# 'rb' = read binary
with open(filename, "rb") as f:
data = pickle.load(f)
return data
dump saves data, load restores data.
test.pyThis is the menu-driven student database program.
import pickleutilities as pt
data = {}
filename = "students.db"
# Step 1: Load old data (if file exists)
try:
data = pt.readFile(filename)
except:
print("No file found. Will create now")
# Step 2: Menu loop
while True:
option = int(input("0-Exit, 1-Insert, 2-Show\\n"))
if option == 0:
break
if option == 1:
rollno = int(input("Enter Roll No\\n"))
name = input("Enter Name\\n")
data[rollno] = name
continue
if option == 2:
for key, value in data.items():
print(key, value, sep=",")
continue
print("Invalid option")
# Step 3: Save data at exit
pt.saveFile(filename, data)
pt.saveFile(filename, data)
This is where your data becomes permanent.
{101: {"name": "Amit", "marks": 82}}
'w' instead of binary mode 'wb'
Then readFile() will raise an error. That is why we use try/except and start with an
empty dictionary on first run.
students.db?
Itβs just a filename. We use .db because it feels like a small local database file.
It is actually a binary pickle file.
Not exactly. Pickle is a simple storage method. Real databases (SQLite, MySQL) provide stronger features like querying, multiple tables, safe concurrent access, etc. But pickle is perfect for learning and small apps.