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", "w") # write mode (overwrites)
f = open("data.txt", "a") # append mode
f = open("data.txt", "r+") # read + write
Reading from a File
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.write("Hello World!\n")
f.writelines(["Line 1\n", "Line 2\n"])
f.close()
The 'with' Statement (Best Practice)
content = f.read()
# File automatically closed here!
with statement — it automatically closes the file, even if an error occurs.
File Handling in Python — MCQ Practice
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!
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