Bird
Raised Fist0

How can you modify this code to skip empty lines while reading a file line by line?

hard🚀 Application Q9 of Q15
Python - File Reading and Writing Strategies
How can you modify this code to skip empty lines while reading a file line by line?
with open('data.txt') as f:
    for line in f:
        print(line.strip())
AOpen file in binary mode
BUse readlines() instead of for loop
CAdd if line.strip(): before print to skip empty lines
DCall strip() after print statement
Step-by-Step Solution
Solution:
  1. Step 1: Identify how to detect empty lines

    line.strip() removes whitespace; if result is empty string, line is empty.
  2. Step 2: Use condition to skip empty lines

    Adding if line.strip(): before print skips lines that are empty after stripping.
  3. Final Answer:

    Add if line.strip(): before print to skip empty lines -> Option C
  4. Quick Check:

    Conditionally print non-empty lines = D [OK]
Quick Trick: Use if line.strip() to skip empty lines [OK]
Common Mistakes:
MISTAKES
  • Printing before stripping
  • Using readlines() unnecessarily
  • Opening file in wrong mode

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes