Python – How to treat the first line of a file differently in Python

fileiterationpython

I often need to process large text files containing headers in the first line. The headers are often treated differently to the body of the file, or my processing of the body is dependent on the headers. Either way I need to treat the first line as a special case.
I could use simple line iteration and set a flag:

headerProcessed = false
for line in f:
    if headerProcessed:
        processBody(line)
    else:
        processHeader(line)
        headerProcessed = true

but I dislike a test in the loop that is redundant for all but one of the millions of times it executes. Is there a better way? Could I treat the first line differently then get the iteration to start on the second line? Should I be bothered?

Best Answer

You could:

processHeader(f.readline())
for line in f:
    processBody(line)