Bird
0
0

What will be the output of this code snippet?

medium📝 Predict Output Q5 of 15
Python - File Reading and Writing Strategies
What will be the output of this code snippet?
with open('data.txt', 'r') as f:
    lines = []
    for _ in range(3):
        lines.append(f.readline().strip())
print(lines)
AA list of the entire file lines
BA syntax error due to missing colon
CAn empty list
DA list of the first 3 lines without newline characters
Step-by-Step Solution
Solution:
  1. Step 1: Understand readline() and loop

    The loop runs 3 times, each time reading one line and stripping whitespace.
  2. Step 2: Collect lines in list and print

    After 3 iterations, lines contains first 3 lines without newline characters.
  3. Final Answer:

    A list of the first 3 lines without newline characters -> Option D
  4. Quick Check:

    Partial file read lines = B [OK]
Quick Trick: readline() reads one line; strip() removes newlines [OK]
Common Mistakes:
  • Expecting entire file lines
  • Forgetting to strip newlines
  • Assuming empty list
  • Syntax errors in loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes