Skip to main content
Unlisted page
This page is unlisted. Search engines will not index it, and only users having a direct link can access it.

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 TypeAnalogyPython Module
Text FilesA handwritten letter ✉️Built-in (open)
Binary FilesA encrypted safe 🔐pickle
CSV FilesA 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

# 🛒 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!")

🧠 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"

TurnMethodResultPointer 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

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir