Bird
0
0

You need to process a huge log file and write only lines containing the word 'ERROR' to a new file. Which approach is best to handle this efficiently?

hard📝 Application Q15 of 15
Python - File Reading and Writing Strategies

You need to process a huge log file and write only lines containing the word 'ERROR' to a new file. Which approach is best to handle this efficiently?

ARead entire file into memory, filter lines, then write all at once
BUse <code>readlines()</code> to get all lines, then write filtered lines
COpen output file in read mode and append lines
DRead file line by line, write matching lines immediately to output file
Step-by-Step Solution
Solution:
  1. Step 1: Avoid loading entire file into memory

    Reading whole file at once uses too much memory for huge files.
  2. Step 2: Process line by line and write incrementally

    Reading each line and writing matching lines immediately saves memory and is efficient.
  3. Final Answer:

    Read file line by line, write matching lines immediately to output file -> Option D
  4. Quick Check:

    Line-by-line processing + incremental write = efficient [OK]
Quick Trick: Filter and write lines one by one to save memory [OK]
Common Mistakes:
  • Loading entire file into memory
  • Using wrong file mode for output
  • Appending to output file opened in read mode

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes