Bird
0
0

What will be the output of the following code if data.txt initially contains Hello?

medium📝 Predict Output Q13 of 15
Python - File Handling Fundamentals
What will be the output of the following code if data.txt initially contains Hello?
with open('data.txt', 'a') as f:
    f.write(' World')

with open('data.txt', 'r') as f:
    print(f.read())
AHello World
BWorld
CHello
DHello\nWorld
Step-by-Step Solution
Solution:
  1. Step 1: Understand the append operation

    The code opens 'data.txt' in append mode and adds ' World' after existing content 'Hello'.
  2. Step 2: Read the updated file content

    Reading the file shows 'Hello World' as the new content without a newline.
  3. Final Answer:

    Hello World -> Option A
  4. Quick Check:

    Appending adds text at end without newline [OK]
Quick Trick: Appending adds text exactly where file ends, no newline added [OK]
Common Mistakes:
  • Expecting a newline between 'Hello' and 'World'
  • Thinking append overwrites existing content
  • Confusing output with just 'World'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes