Bird
0
0

Find the error in this code snippet:

medium📝 Debug Q6 of 15
Python - File Handling Fundamentals
Find the error in this code snippet:
file = open('data.txt', 'r')
file.write('Hello')
AMissing file.close()
BFile name is incorrect
CFile opened in read mode cannot be written to
Dwrite() method does not exist
Step-by-Step Solution
Solution:
  1. Step 1: Check file mode used

    The file is opened in 'r' (read) mode, which does not allow writing.
  2. Step 2: Understand write() usage

    Calling write() on a file opened in read mode causes an error because writing is not permitted.
  3. Final Answer:

    File opened in read mode cannot be written to -> Option C
  4. Quick Check:

    Write requires 'w' or 'a' mode [OK]
Quick Trick: Open file in 'w' or 'a' to write [OK]
Common Mistakes:
  • Ignoring file mode restrictions
  • Assuming write() works in read mode
  • Confusing missing close() with write error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes