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

Peter Otten __peter__ at web.de
Mon Aug 16 05:59:57 EDT 2010


Egbert Bouwman wrote:

> Often the first line of a file tells how to read or interpret the other
> lines.
> 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.close()
> 
> f = open(file_name,"r")        # tweede opening
> if not special:
>     # use first line, read previously
>     stripped_line = file_line.strip()
> else:
>     # skip first file_line, or treat in another special way:
>     f.next()
>     # read other lines:
>     for file_line in f:
>         stripped_line = file_line.strip()
>         # now do something with stripped_line
> f.close()

with open(filename) as lines:
    first_line = next(lines, "")
    if special(first_line):
        # ...
    else:
        lines = itertools.chain([first_line], lines)
    for line in lines:
        # ...



More information about the Python-list mailing list