loops - How do I get python to read only every other line from a file that contains a poem -
i know code reading every line
f=open ('poem.txt','r') line in f: print line
how have python read even-numbered lines original file. assuming 1-based numbering of lines.
there quite few different ways, here simple one
with open('poem.txt', 'r') f: count = 0 line in f: count+=1 if count % 2 == 0: #this remainder operator print(line)
this might little nicer, saving lines declaring , incrementing count:
with open('poem.txt', 'r') f: count, line in enemerate(f): if count % 2 == 0: print(line)
Comments
Post a Comment