Bird
0
0

What will be the output of this code if 'sample.txt' contains:\nHello\nWorld\nPython\n?

medium📝 Predict Output Q4 of 15
Python - File Reading and Writing Strategies
What will be the output of this code if 'sample.txt' contains:\nHello\nWorld\nPython\n?
with open('sample.txt') as f:
    for line in f:
        print(line.strip())
AHello\nWorld\nPython
BHello World Python
CHello\nWorld\nPython\n\n
DHello World Python
Step-by-Step Solution
Solution:
  1. Step 1: Understand the loop and strip()

    Loop reads each line including newline; strip() removes whitespace including newlines.
  2. Step 2: Print each stripped line separately

    Each line prints on its own line without extra spaces or newlines.
  3. Final Answer:

    Hello World Python -> Option D
  4. Quick Check:

    strip() removes newlines, prints lines separately = C [OK]
Quick Trick: strip() removes newline characters from each line [OK]
Common Mistakes:
  • Ignoring strip() effect
  • Expecting all lines in one print
  • Confusing print behavior with newlines

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes