Bird
Raised Fist0

You have a list lines = ['First\n', 'Second\n', 'Third\n']. Which code snippet efficiently appends all lines to log.txt?

hard🚀 Application Q8 of Q15
Python - File Handling Fundamentals
You have a list lines = ['First\n', 'Second\n', 'Third\n']. Which code snippet efficiently appends all lines to log.txt?
Awith open('log.txt', 'a') as f: f.writelines(lines)
Bwith open('log.txt', 'w') as f: for line in lines: f.write(line)
Cwith open('log.txt', 'r') as f: f.writelines(lines)
Dwith open('log.txt', 'a') as f: for line in lines: f.read(line)
Step-by-Step Solution
Solution:
  1. Step 1: Append mode

    Mode 'a' appends data without erasing existing content.
  2. Step 2: Efficient writing

    Using f.writelines(lines) writes all lines efficiently.
  3. Step 3: Check other options

    'w' overwrites file, 'r' mode disallows writing, f.read() is for reading.
  4. Final Answer:

    with open('log.txt', 'a') as f: f.writelines(lines) -> Option A
  5. Quick Check:

    Use 'a' mode and writelines() to append multiple lines [OK]
Quick Trick: Use 'a' mode with writelines() to append lists [OK]
Common Mistakes:
MISTAKES
  • Using 'w' mode which overwrites file
  • Trying to write in 'r' mode
  • Using read() instead of write()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes