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¶
graph LR
A[Open File π] --> B[Read/Write βοΈ]
B --> C[Close File π]
style C fill:#f96,stroke:#333
π» Implementation: The Logging Lab¶
") f.write("It was easier than I thought. β ")
print("Journal updated!")
```
π§ 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