如何让 python 只读取包含一首诗的文件中的每隔一行

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

我知道读取每一行的代码是

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

如何让 python 只读取原始文件中的偶数行。假设基于 1 的行编号。

方法有很多种,这里简单介绍一种

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)

这也可能更好一些,省去了声明和递增计数的行:

with open('poem.txt', 'r') as f:
    for count, line in enumerate(f, start=1):
        if count % 2 == 0:
            print(line)

来自

with open('poem.txt', 'r') as f:
    for count, line in enumerate(f, start=1):
        if count % 2 == 0:
            print line