Bird
Raised Fist0

You want to keep a log of events in a file without losing old logs. Which code snippet correctly appends new logs without overwriting existing ones?

medium🚀 Application Q15 of Q15
Python - File Reading and Writing Strategies
You want to keep a log of events in a file without losing old logs. Which code snippet correctly appends new logs without overwriting existing ones?
Awith open('log.txt', 'w') as f: f.write('New event\n')
Bwith open('log.txt', 'a') as f: f.write('New event\n')
Cwith open('log.txt', 'r') as f: f.write('New event\n')
Dwith open('log.txt', 'x') as f: f.write('New event\n')
Step-by-Step Solution
Solution:
  1. Step 1: Understand log file needs

    Logs should be added without deleting old entries, so appending is needed.
  2. Step 2: Choose correct mode

    Mode 'a' appends data; 'w' overwrites, 'r' is read-only, 'x' creates new file and errors if exists.
  3. Final Answer:

    with open('log.txt', 'a') as f: f.write('New event\n') -> Option B
  4. Quick Check:

    Append mode 'a' preserves old data [OK]
Quick Trick: Use 'a' mode to add without deleting old logs [OK]
Common Mistakes:
MISTAKES
  • Using 'w' and losing old logs
  • Trying to write in 'r' mode
  • Using 'x' which fails if file exists

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes