Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Context Managers
What will be the output of this code?
with open('sample.txt', 'w') as f:
    f.write('Hi')
print(f.closed)
AError: f is not defined
BTrue
CFalse
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Understand the scope of the file object

    The variable f exists outside the with block but the file is closed after the block.
  2. Step 2: Check the closed attribute

    After the block, f.closed is True because the file is closed automatically.
  3. Final Answer:

    True -> Option B
  4. Quick Check:

    File closed after with block = True [OK]
Quick Trick: File closed attribute is True after with block ends [OK]
Common Mistakes:
  • Assuming file stays open
  • Thinking f is undefined
  • Expecting False instead of True

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes