Ready
Your guide has been resting for a day
Turn the avatar back on if you want help with doubts, hints, and step-by-step guidance.
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
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()
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()
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!
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