Skip to content

Chapter 2: File Handling in Python πŸš€ΒΆ

CBSE Class 12 Computer SciencePython File Handling

Recommended order: Class 12 overview -> File Handling -> Stack and Queue -> SQL practice

Best for: CBSE Class 12 students preparing Python and practical exam topics

Prerequisites: Python Basics

Mentor's Note: Usually, a program's memory is like a dreamβ€”it vanishes when you wake up (close the program). File Handling is how we write things down in a diary so the computer remembers them forever! πŸ’‘


🌟 The Scenario: The Digital Filing Cabinet πŸ—„οΈΒΆ

Imagine you are a clerk in a busy government office.

  • The Data: You have hundreds of applications (Data in variables). πŸ“¦
  • The File: You don't want to hold them in your hands all day. You put them into a Folder (The File) and store it in a Cabinet (The Hard Drive). πŸ“¦
  • The Result: Even if you go home and come back tomorrow, the data is still there! This is Persistence. βœ…

πŸ“– Concept ExplanationΒΆ

1. Types of FilesΒΆ

File Type Analogy Python Module
Text Files A handwritten letter βœ‰οΈ Built-in (open)
Binary Files A encrypted safe πŸ” pickle
CSV Files A simple spreadsheet πŸ“Š csv

2. File Modes (The "Action" code)ΒΆ

  • 'r': Read (Open to look).
  • 'w': Write (Starts fresh, deletes old content!). ⚠️
  • 'a': Append (Adds to the end). βž•

🎨 Visual Logic: The File Lifecycle¢

graph LR
    A[Open File πŸ“‚] --> B[Read/Write βš™οΈ]
    B --> C[Close File πŸ”’]

    style C fill:#f96,stroke:#333

πŸ’» Implementation: The Logging LabΒΆ

```python

πŸ›’ Scenario: Keeping a Daily JournalΒΆ

πŸš€ Action: Appending text to a fileΒΆ

Using 'with' is best practice (Auto-closes!) πŸ”’ΒΆ

with open("diary.txt", "a") as f: f.write("Today I learned Python File Handling! 🐍

") f.write("It was easier than I thought. βœ… ")

print("Journal updated!")
```
# πŸ›’ Scenario: Saving a Game High Score
import pickle

# πŸš€ Action: Dumping an object into binary
data = {"player": "Vishnu", "score": 999}

with open("save.dat", "wb") as f:
    pickle.dump(data, f)

🧠 Step-by-Step Logic¢

  1. Start 🏁
  2. Open: Connect the program to the file using open().
  3. Mode: Specify if you are reading or writing.
  4. Action: Use .read(), .write(), or pickle.load().
  5. Close: Disconnect the file to save energy and memory.
  6. End 🏁

πŸ“Š Sample Dry Run (Read)ΒΆ

File content: "Hi Bye"

Turn Method Result Pointer Position
1 .readline() `"Hi
"` End of line 1 πŸ“
2 .readline() "Bye" End of file πŸ“

πŸ“‰ Technical AnalysisΒΆ

  • The Pointer: Python uses a "Cursor" (File Pointer) to track where it is in the file. ☝️
  • Performance: Reading line-by-line is memory-efficient for huge files. 🏎️

🎯 Practice Lab πŸ§ͺΒΆ

Task: The Word Counter

Task: Write a program that reads a file story.txt and counts how many times the word "Python" appears. Hint: content.count("Python"). πŸ’‘


πŸ’‘ Board Exam Focus (CBSE Class 12) πŸ‘”ΒΆ

  • Important: You will almost certainly get a question on writelines() vs write().
  • Answer: write() takes one string; writelines() takes a list of strings!

πŸ’‘ Pro Tip: "Data is what you need to do analytics. Information is what you need to do a business." - John Cann


πŸ“ˆ Learning PathΒΆ