Bird
Raised Fist0

Find the error in this code snippet:

medium📝 Debug Q14 of Q15
Python - Context Managers

Find the error in this code snippet:

file = open('log.txt', 'w')
file.write('Start logging')
# forgot to close the file
AFile is not opened in read mode.
BFile name should be a variable.
CFile write syntax is incorrect.
DFile is not closed after writing.
Step-by-Step Solution
Solution:
  1. Step 1: Check file opening and writing

    The file is opened correctly in write mode and data is written properly.
  2. Step 2: Identify missing resource management

    The file is not closed after writing, which can cause data loss or resource leaks.
  3. Final Answer:

    File is not closed after writing. -> Option D
  4. Quick Check:

    Always close files after use [OK]
Quick Trick: Always close files or use with [OK]
Common Mistakes:
MISTAKES
  • Ignoring missing close() call
  • Thinking write syntax is wrong
  • Confusing file modes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes