Bird
0
0

What is wrong with this code snippet that tries to write 'Hello' to 'file.txt'?

medium📝 Debug Q14 of 15
Python - File Handling Fundamentals
What is wrong with this code snippet that tries to write 'Hello' to 'file.txt'?
file = open('file.txt', 'w')
file.write('Hello')
AThe file is not opened in write mode.
Bwrite() method is used incorrectly.
CThe file is not closed after writing.
DThe filename should be a variable, not a string.
Step-by-Step Solution
Solution:
  1. Step 1: Check file opening mode

    The file is opened with 'w' mode, which is correct for writing.
  2. Step 2: Check file closing

    The code does not close the file after writing, which can cause data loss or resource leaks.
  3. Final Answer:

    The file is not closed after writing. -> Option C
  4. Quick Check:

    Always close files or use with block [OK]
Quick Trick: Always close files or use with to avoid data loss [OK]
Common Mistakes:
  • Forgetting to close the file
  • Using wrong mode for writing
  • Misusing write() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes