Teacher: Champak Roy
In this lesson, students learned how to make Python remember data even after the program closes using the pickle module.
Conclusion:
Variables = temporary ❌
Files = permanent ✅
One-line formula:
Python Object → Bytes → File
pickleutilities.pyThis file handles saving and reading data.
import pickle
def saveFile(filename, data):
with open(filename, 'wb') as file:
pickle.dump(data, file)
def readFile(filename):
with open(filename, "rb") as f:
return pickle.load(f)
Important:
dump() saves data,
load() restores data.
test.pyMenu-driven student database program.
import pickleutilities as pt
data = {}
filename = "students.db"
try:
data = pt.readFile(filename)
except:
print("No file found. Will create now")
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
if option == 2:
for k, v in data.items():
print(k, v, sep=", ")
pt.saveFile(filename, data)
Most important line:
pt.saveFile(filename, data)
This makes the data permanent.
You can run and test this program directly using the embedded Python editor below.
👉 Create two files inside the editor:
pickleutilities.py and test.py
Teacher’s Line:
“Aaj tumne Python ko yaad rakhna sikha diya.”