Python Learning Series · @onlysamarrr · Day 26 / 30

Day 26: File Handling

Day 26 teaches file handling. open() opens a file: 'w' writes and erases old content, 'a' appends, 'r' reads. The with statement closes the file automatically, so you never forget close().

Phase: Intermediate · Reels: 126/450 – 130/450

Quick Answer

Day 26 teaches file handling. open() opens a file: 'w' writes and erases old content, 'a' appends, 'r' reads. The with statement closes the file automatically, so you never forget close().

What You Will Learn

Code

with open("notes_demo.txt", "w", encoding="utf-8") as f:
    f.write("Line 1\nLine 2\n")
with open("notes_demo.txt", "a", encoding="utf-8") as f:
    f.write("Line 3\n")
with open("notes_demo.txt", encoding="utf-8") as f:
    lines = f.readlines()
print(len(lines))
print(lines)

Output

3
['Line 1\n', 'Line 2\n', 'Line 3\n']

Code Explained, Line by Line

  1. open(..., "w") creates a new file or erases an existing file's content before writing.
  2. open(..., "a") appends: old content stays, new content is added at the end.
  3. encoding="utf-8" keeps Hindi and emoji text safe.
  4. with closes the file automatically when its block ends, so close() cannot be forgotten.
  5. readlines() returns all lines as a list; in the example there are 3 lines.
Common Mistake: Mode 'w' deletes the file's old content immediately. To add without deleting, use 'a', or your data is gone.

Real-Life Use

Logs, notes apps and saved settings all write to files.

Practice Task: Build a notes app: save lines to a file, then count how many lines it has.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. What does open("f.txt", "w") do to existing content?

Q2. Which mode appends without erasing?

Q3. Why use with when opening a file?

Today's 5 Reels (from the 90-Day Plan Excel)

126/450Conceptopen, read, write
127/450Live demoNotes app file mein save
128/450Common mistakeMode w file mita deta
129/450QuizQuiz: lines count karo
130/450Interview / real lifeReal life: logs likhna
← Day 25Day 27 →