🏫 7 PM Class Notes β€’ Python Persistence

Python Pickle: Save Data Permanently (Student Database Mini Project)

Today we learned how to make Python β€œremember” data even after the program closes β€” using pickle (serialization).

What you builtMenu-driven student database
Core skillSerialization + file storage
ConceptRAM is temporary, files are permanent
Key idea: Pickle converts a Python object (like a dictionary) into bytes, stores it in a file, and later loads it back into Python memory.

1) Why we need Pickle

  • Variables live in RAM β†’ when the program ends, data is lost.
  • Files live on disk β†’ data stays even after closing the program.
  • Real apps (student systems, billing, attendance, notes apps) require permanent storage.

2) What is Pickle?

Pickle is a built-in Python module used for serialization:

  • dump β†’ save Python object to a binary file
  • load β†’ read binary file and rebuild the Python object
One-line formula: Python object β†’ bytes β†’ file

3) Project Flow (Understand this well)

  1. When program starts: try to load old data from file.
  2. If file not found: start with an empty dictionary.
  3. User inserts students (rollno β†’ name).
  4. At exit: save the dictionary to file.
  5. Next run: the program loads data again β€” nothing is lost.

Quick Check βœ…

  • What does 'wb' mean?
  • What does pickle.dump() do?
  • Why do we need try/except?
  • What does 'rb' mean?

Try This Today

  1. Run the program, insert 2 students, exit.
  2. Run again and choose β€œShow” β€” data should still be there.

Important Note ⚠️

Pickle is perfect for learning + offline storage. But do not use pickle files from unknown sources β€” it can be unsafe.

4) Code File #1 β€” pickleutilities.py

This file contains two helper functions: saveFile and readFile.

Copy & paste into: pickleutilities.py
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
Remember: dump saves data, load restores data.

5) Code File #2 β€” test.py

This is the menu-driven student database program.

Copy & paste into: test.py
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)
Most important line: pt.saveFile(filename, data) This is where your data becomes permanent.

6) Homework (Submit tomorrow)

  1. Delete option: Add a new menu option to delete a student by roll number.
  2. Store marks: Save name + marks like this:
    {101: {"name": "Amit", "marks": 82}}
  3. Thinking question: Why should we NOT store passwords using pickle?

7) Common Mistakes (Avoid)

FAQ

Q1) What if the file does not exist?

Then readFile() will raise an error. That is why we use try/except and start with an empty dictionary on first run.

Q2) Why is the file called 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.

Q3) Is pickle the same as a real database?

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.