Bird
0
0

You want to read a file and create a list of all non-empty lines without newline characters. Which code correctly does this?

hard📝 Application Q15 of 15
Python - File Handling Fundamentals
You want to read a file and create a list of all non-empty lines without newline characters. Which code correctly does this?
Awith open('log.txt', 'r') as f: lines = [line.strip() for line in f if line.strip()]
Bwith open('log.txt', 'r') as f: lines = [line for line in f.readlines() if line != '\n']
Cwith open('log.txt', 'r') as f: lines = f.read().split('\n')
Dwith open('log.txt', 'r') as f: lines = [line.rstrip('\n') for line in f.readlines()]
Step-by-Step Solution
Solution:
  1. Step 1: Remove whitespace and filter empty lines

    Using line.strip() removes spaces and newline characters from both ends. The condition if line.strip() filters out empty lines.
  2. Step 2: Use list comprehension on file object

    Iterating directly on the file object reads line by line efficiently. This creates a list of cleaned, non-empty lines.
  3. Final Answer:

    with open('log.txt', 'r') as f: lines = [line.strip() for line in f if line.strip()] -> Option A
  4. Quick Check:

    strip() + filter empty lines = clean list [OK]
Quick Trick: Use strip() and filter with if line.strip() in comprehension [OK]
Common Mistakes:
  • Not stripping newline characters
  • Including empty lines in the list
  • Using read() then splitting without filtering empty lines

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes