Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Standard Library Usage
What will be the output of this code?
with open('sample.txt', 'w') as f:
    f.write('123')
with open('sample.txt', 'a') as f:
    f.write('456')
with open('sample.txt', 'r') as f:
    print(f.read())
A123456
B456
C123
DError
Step-by-Step Solution
Solution:
  1. Step 1: Write '123' to file in write mode

    The first block opens the file in 'w' mode, which creates or overwrites the file with '123'.
  2. Step 2: Append '456' to the file

    The second block opens the file in 'a' mode, adding '456' to the end, so file content becomes '123456'.
  3. Step 3: Read and print the file content

    The third block reads the entire file and prints '123456'.
  4. Final Answer:

    123456 -> Option A
  5. Quick Check:

    Write + Append = combined content [OK]
Quick Trick: Write mode overwrites; append mode adds at end [OK]
Common Mistakes:
  • Assuming append overwrites
  • Expecting only last write
  • Confusing read mode output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes