3

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.

Maria chalsev
  • 53
  • 1
  • 2
  • 5

2 Answers2

7

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)
Daniel Slater
  • 4,123
  • 4
  • 28
  • 39
  • This is definitely correct, although the pythonic way to open the file would be with a context manager, such that `with open('poem.txt', 'r') as f:` would be what you want (that way the file is closed properly if you crash, etc. – Nick Bastin May 30 '15 at 22:33
  • Yeah, your right, should show best practice, have amended. – Daniel Slater May 30 '15 at 22:34
  • 3
    Of course in the land of best practice one should also use `enumerate`: `for count,line in enumerate(f, start=1): if count % 2 == 0...` and thus avoid creating or incrementing the counter yourself. :-) – Nick Bastin May 30 '15 at 23:14
3

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81