Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - File Reading and Writing Strategies
What will be the output of this code?
with open('data.txt', 'w') as f:
    f.write('Hello')
with open('data.txt', 'a') as f:
    f.write(' World')
with open('data.txt', 'r') as f:
    print(f.read())
AHello
BHello World
C World
DError: file not found
Step-by-Step Solution
Solution:
  1. Step 1: Write 'Hello' with 'w' mode

    File is created or overwritten with 'Hello'.
  2. Step 2: Append ' World' with 'a' mode

    ' World' is added after existing 'Hello'.
  3. Step 3: Read and print file content

    Reading shows combined string 'Hello World'.
  4. Final Answer:

    Hello World -> Option B
  5. Quick Check:

    Write then append = combined text [OK]
Quick Trick: Write with 'w', then append with 'a' adds text [OK]
Common Mistakes:
  • Assuming append overwrites
  • Expecting only 'Hello' output
  • Thinking file is missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes