When the first line of a file tells something about the other lines

Egbert Bouwman egbert.bouwman at xs4all.nl
Mon Aug 16 11:44:56 CEST 2010

Often the first line of a file tells how to read or interpret the other
Depending on the result, you then have to ...
- skip the first line, or
- treat the first line in another special way, or
- treat the first line in the same way as the other lines.

I can handle this by opening the file twice,
the first time for reading the first line only.
I suppose there exists a more elegant solution.
Below is the structure of what I do now.
Please comment.

f = open(file_name,"r")        # eerste opening
file_line  = f.readline()
special = True if some_condition else False

f = open(file_name,"r")        # tweede opening
if not special:
    # use first line, read previously
    stripped_line = file_line.strip()
    # skip first file_line, or treat in another special way:
    # read other lines:
    for file_line in f:
        stripped_line = file_line.strip()
        # now do something with stripped_line

Egbert Bouwman  
Keizersgracht 197-II    
1016 DS  Amsterdam      
Tel 0(031)20 6257991

More information about the Python-list mailing list