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

E

Egbert Bouwman

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()

egbert
 
E

egbert

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

Beautiful. And a nice suggestion to read the itertools docs.
egbert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top