🎓 Senior Secondary
| CBSE • Computer Science

File Handling in Python

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

1 Lesson 1 MCQ
+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

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.