关于循环:如何让python只读取包含诗的文件中的每一行

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

我知道每一行的代码是

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

如何让python从原始文件中只读偶数行。假设以1为基础的行编号。


有很多不同的方法,这里有一个简单的

1
2
3
4
5
6
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)

这也可能更好一点,保存用于声明和增加计数的行:

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


来自尼克·巴斯汀的评论:

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