Bird
Raised Fist0

What will be the output of this code snippet?

medium📝 Predict Output Q4 of Q15
Python - Context Managers
What will be the output of this code snippet?
with open('test1.txt', 'w') as file1, open('test2.txt', 'w') as file2:
    file1.write('Data1')
    file2.write('Data2')
print(file1.closed, file2.closed)
AFalse True
BFalse False
CTrue False
DTrue True
Step-by-Step Solution
Solution:
  1. Step 1: Understand the with statement

    The with statement automatically closes the files after the block is executed.
  2. Step 2: Check the file closed attribute

    After the with block, both file1 and file2 are closed, so file1.closed and file2.closed are both True.
  3. Final Answer:

    True True -> Option D
  4. Quick Check:

    Files are closed after with block ends [OK]
Quick Trick: Files close automatically after with block [OK]
Common Mistakes:
MISTAKES
  • Assuming files remain open after with block
  • Confusing file.closed attribute value
  • Thinking only one file closes automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes