Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get python to read only every other line from a file that contains a poem

Tags:

file

loops

lines

I know the code for reading every line is

f=open ('poem.txt','r')
for line in f: 
    print line 

how do you have python read only even-numbered lines from the original file. Assuming 1-based numbering of lines.

like image 408
Maria chalsev Avatar asked Dec 04 '25 23:12

Maria chalsev


2 Answers

There are quite a few different ways, here a simple one

with open('poem.txt', 'r') as f:
    count = 0
    for line in f:
        count+=1
        if count % 2 == 0: #this is the remainder operator
            print(line)

This also might be a little nicer, saving the lines for declaring and incrementing the count:

with open('poem.txt', 'r') as f:
    for count, line in enumerate(f, start=1):
        if count % 2 == 0:
            print(line)
like image 176
Daniel Slater Avatar answered Dec 06 '25 17:12

Daniel Slater


From Nick Bastin's comment:

with open('poem.txt', 'r') as f:
    for count, line in enumerate(f, start=1):
        if count % 2 == 0:
            print line
like image 45
wjandrea Avatar answered Dec 06 '25 16:12

wjandrea