Bird
0
0

Find the error in this code snippet:

medium📝 Debug Q14 of 15
Python - Context Managers
Find the error in this code snippet:
f = open('data.txt', 'r')
print(f.read())
# forgot to close the file

How can a context manager fix this?
AUse <code>with open('data.txt', 'r') as f:</code> to auto-close
BAdd <code>f.close()</code> after print
CUse <code>open('data.txt', 'r')</code> without assignment
DNo fix needed, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Identify missing resource cleanup

    The file is opened but never closed, risking resource leaks.
  2. Step 2: Use context manager for automatic closing

    Using 'with' ensures the file closes automatically after the block ends, even if errors occur.
  3. Final Answer:

    Use with open('data.txt', 'r') as f: to auto-close -> Option A
  4. Quick Check:

    Context managers auto-close files = Use with open('data.txt', 'r') as f: to auto-close [OK]
Quick Trick: Use 'with' to avoid forgetting to close files [OK]
Common Mistakes:
  • Forgetting to call f.close() manually
  • Thinking open() auto-closes files
  • Ignoring resource leaks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes