Bird
Raised Fist0

The following code is intended to append a new line to notes.txt. What is the error?

medium📝 Debug Q14 of Q15
Python - File Handling Fundamentals
The following code is intended to append a new line to notes.txt. What is the error?
with open('notes.txt', 'a') as file:
    file.write('New note')
    file.write('\n')
AThe write method cannot be called twice on the same file object.
BNo error; code appends 'New note' and a newline correctly.
CThe file should be opened in 'w' mode to append data.
DThe newline character should be '\\r\\n' for Windows compatibility.
Step-by-Step Solution
Solution:
  1. Step 1: Check file mode and write calls

    The file is opened in append mode 'a', which is correct for adding data.
  2. Step 2: Verify writing multiple times

    Calling write twice is allowed; first writes 'New note', second writes a newline '\n'.
  3. Final Answer:

    No error; code appends 'New note' and a newline correctly. -> Option B
  4. Quick Check:

    Multiple writes in append mode work fine [OK]
Quick Trick: Multiple writes allowed; 'a' mode appends safely [OK]
Common Mistakes:
MISTAKES
  • Thinking 'w' mode is needed to append
  • Believing write() can be called only once
  • Confusing newline characters for error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes