Bird
0
0

Why is reading a large file line by line using a for loop over the file object more memory efficient than using readlines()?

hard📝 Conceptual Q10 of 15
Python - File Reading and Writing Strategies
Why is reading a large file line by line using a for loop over the file object more memory efficient than using readlines()?
ABecause readlines() loads all lines into memory at once
BBecause for loop reads the entire file at once
CBecause readlines() reads only one line at a time
DBecause for loop converts lines to bytes automatically
Step-by-Step Solution
Solution:
  1. Step 1: Understand readlines() behavior

    readlines() reads all lines into a list, loading the entire file into memory.
  2. Step 2: Understand for loop over file object

    Iterating over the file object reads one line at a time, using less memory.
  3. Final Answer:

    Because readlines() loads all lines into memory at once -> Option A
  4. Quick Check:

    Memory use difference = C [OK]
Quick Trick: For loop reads lines lazily; readlines() loads all [OK]
Common Mistakes:
  • Thinking readlines() reads one line
  • Believing for loop reads whole file
  • Confusing bytes and strings
  • Assuming automatic conversion

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes