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

Mar*_*sev 1 loops file lines

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

f=open ('poem.txt','r')
for line in f: 
    print line 
Run Code Online (Sandbox Code Playgroud)

你怎么让python只读取原始文件中的偶数行.假设基于1的行号.

Dan*_*ter 5

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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

  • 当然在最佳实践的土地上,还应该使用`enumerate`:`for count,line in enumerate(f,start = 1):if count%2 == 0 ...`从而避免创建或递增计数器你自己.:-) (3认同)