Chapter 2: File Handling in Python 🚀
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
💻 Implementation: The Logging Lab
- Text Files
- Binary Files (Pickle)
# 🛒 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! 🐍\n")
f.write("It was easier than I thought. ✅\n")
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
- Start 🏁
- Open: Connect the program to the file using
open(). - Mode: Specify if you are reading or writing.
- Action: Use
.read(),.write(), orpickle.load(). - Close: Disconnect the file to save energy and memory.
- 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()vswrite(). - 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