🏫 7 PM Class Notes

Python Pickle — Save Data Permanently

Teacher: Champak Roy

In this lesson, students learned how to make Python remember data even after the program closes using the pickle module.

1️⃣ Why This Lesson Is Important

Conclusion:
Variables = temporary ❌
Files = permanent ✅

2️⃣ What is Pickle?

One-line formula:

Python Object → Bytes → File

3️⃣ Program Flow (Understand This Clearly)

  1. Try loading old data from file
  2. If file not found → start fresh
  3. User inserts or views students
  4. At exit → data is saved
  5. Next run → data is restored

4️⃣ Code File: pickleutilities.py

This 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.

5️⃣ Code File: test.py

Menu-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.

6️⃣ Run the Code Online (Practice Here)

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

7️⃣ Homework

  1. Add a Delete Student option
  2. Store name + marks together
  3. Think: Why should we NOT store passwords using pickle?

8️⃣ Student Self-Checklist

9️⃣ What’s Next?

Teacher’s Line:
“Aaj tumne Python ko yaad rakhna sikha diya.”