CompTIA Linux+ XK0-006 (V8) Practice Question

On a production Linux server, a Python 3.12 script that parses a multi-gigabyte log file is repeatedly killed by the OOM killer. A simplified version of the offending function is:

def load_logs(path):
    with open(path) as f:
        return [line.strip() for line in f]

The rest of the program processes each line only once and never needs the whole list in memory. Which modification will most directly prevent the excessive memory usage while keeping the code idiomatic and easy to maintain?

  • Rewrite the function as a generator:

    def load_logs(path):
        with open(path) as f:
            for line in f:
                yield line.strip()
    
  • Keep the function as is but slice the list into 1 000-line chunks before processing.

  • Add import gc and call gc.collect() immediately after process(logs) to force garbage collection.

  • Open the file in binary mode to reduce per-line memory: with open(path, 'rb') as f:

CompTIA Linux+ XK0-006 (V8)
Automation, Orchestration, and Scripting
Your Score:
Settings & Objectives
Random Mixed
Questions are selected randomly from all chosen topics, with a preference for those you haven’t seen before. You may see several questions from the same objective or domain in a row.
Rotate by Objective
Questions cycle through each objective or domain in turn, helping you avoid long streaks of questions from the same area. You may see some repeat questions, but the distribution will be more balanced across topics.

Check or uncheck an objective to set which questions you will receive.

Bash, the Crucial Exams Chat Bot
AI Bot