Bird
Raised Fist0

You want to read all lines from a file and store them in a list without newline characters. Which code correctly does this?

hard🚀 Application Q9 of Q15
Python - Standard Library Usage
You want to read all lines from a file and store them in a list without newline characters. Which code correctly does this?
Awith open('data.txt') as f: lines = f.read()
Bwith open('data.txt') as f: lines = f.readlines()
Cwith open('data.txt') as f: lines = f.read().split('\n')
Dwith open('data.txt') as f: lines = [line.strip() for line in f]
Step-by-Step Solution
Solution:
  1. Step 1: Understand reading lines with no newlines

    line.strip() removes newline characters and spaces from each line.
  2. Step 2: Check list comprehension usage

    Using a list comprehension over the file object reads lines one by one and strips them.
  3. Step 3: Analyze other options

    readlines() keeps newlines, read() returns whole text, and splitting may leave empty strings.
  4. Final Answer:

    List comprehension with strip -> Option D
  5. Quick Check:

    Strip removes newlines from each line [OK]
Quick Trick: Use list comprehension with strip() to clean lines [OK]
Common Mistakes:
MISTAKES
  • Using readlines() keeps newlines
  • Splitting read() may cause empty lines
  • Not stripping newlines

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes