Graceful handling of first line

Alex Martelli aleaxit at
Fri Oct 8 11:59:32 CEST 2004

Egbert Bouwman <egbert.list at> wrote:

> A file is too large to fit into memory.
> The first line must receive a special treatment, because 
> it contains  information about how to handle the rest of the file.
> Of course it is not difficult to test if you are reading the first line
> or another one, but it hurts my feelings to do a test which by definition
> succeeds at the first record, and never afterwards.

option 1, the one I would use:

thefile = open('somehugefile.txt')
first_line =
for line in thefile:

this requires Python 2.3 or better, so that thefile IS-AN iterator; in
2.2, get an iterator with foo=iter(thefile) and use .next and for on
that (better still, upgrade!).

option 2, not unreasonable (not repeating the open & calls...):

first_line = thefile.readline()
for line in thefile: ...

option 3, a bit cutesy:

for first_line in thefile: break
for line in thefile: ...

(again, in 2.2 you'll need some foo=iter(thefile)).

I'm sure there are others, but 3 is at least 2 too many already,


More information about the Python-list mailing list