🎓 Senior Secondary
| CBSE • Computer Science

File Handling in Python

Text files, binary files, CSV files — read/write operations.

1 Lesson 1 MCQ 1 Mnemonic
+30
XP
Available to earn
1
Lesson

File Handling in Python — Complete Lesson

File Handling in Python

Files allow us to store data permanently. Python provides built-in functions to read, write, and manage files.

Opening a File

f = open("data.txt", "r")  # read mode
f = open("data.txt", "w")  # write mode (overwrites)
f = open("data.txt", "a")  # append mode
f = open("data.txt", "r+") # read + write

Reading from a File

f = open("data.txt", "r")
content = f.read()       # reads entire file
line = f.readline()      # reads one line
lines = f.readlines()    # returns list of lines
f.close()

Writing to a File

f = open("output.txt", "w")
f.write("Hello World!\n")
f.writelines(["Line 1\n", "Line 2\n"])
f.close()

The 'with' Statement (Best Practice)

with open("data.txt", "r") as f:
    content = f.read()
# File automatically closed here!
Best Practice: Always use with statement — it automatically closes the file, even if an error occurs.
2
MCQ Practice

File Handling in Python — MCQ Practice

3
Memory Trick

File Handling in Python — Mnemonic

Mnemonic 1: File Modes Made Easy 🎉

"Ram Wears Amazing Xylophone"

  • R - 'r' (Read mode) 📖
  • W - 'w' (Write mode) ✍️
  • A - 'a' (Append mode) ➕
  • X - 'x' (Create mode, exclusive) 🆕

Just remember Ram’s funky Xylophone to recall file modes quickly!

Mnemonic 2: Hindi Rhyming Trick for File Operations 📂

"File kholo, data kholo, likho, jodo, aur band karo!"

  • File kholo - open() function to open file 🔓
  • Data kholo - read() to read data 📖
  • Likho - write() to write data ✍️
  • Jodo - append() mode to add data ➕
  • Aur band karo - close() to close file 🔒

This fun Hindi rhyme helps you remember the sequence of file handling steps!

Mnemonic 3: Acronym for File Handling Steps 🚀

O.R.W.A.C“Open Read Write Append Close”

  • O - open()
  • R - read()
  • W - write()
  • A - Append mode (using 'a')
  • C - close()

Remember “ORWAC” like a cool code to ace your file handling questions!

Interactive

Mission: Master This Topic!

Reinforce what you learned with fun activities

🎯

Ready to Battle? Test Your Knowledge!

Practice MCQs, build combos, climb the leaderboard!

Start Practice

Loading...

Hey! 🔥 Your 7-day streak is at risk. Complete one quick quest today?

Streak broken? No worries. Recover with bonus XP by completing a quest now.