蟒蛇。文本文件中的偶数行

时间:2013-07-28 12:42:51

标签: python

所以,我需要一个代码来从txt文件中只读取偶数行。 这是一个任务的例子。

输入:

Bravely bold Sir Robin rode forth from Camelot
Yes, brave Sir Robin turned about
He was not afraid to die, O brave Sir Robin
And gallantly he chickened out
He was not at all afraid to be killed in nasty ways
Bravely talking to his feet
Brave, brave, brave, brave Sir Robin
He beat a very brave retreat

输出:

Yes, brave Sir Robin turned about
And gallantly he chickened out
Bravely talking to his feet
He beat a very brave retreat

4 个答案:

答案 0 :(得分:3)

使用itertools.islice

import itertools
import sys

with open('input.txt') as f:
    sys.stdout.writelines(itertools.islice(f, 1, None, 2))

答案 1 :(得分:3)

所以,只输出偶数行。

i = 1
f = open('file')
for line in f.readlines():
    if i % 2 == 0 :
        print line
    i += 1

答案 2 :(得分:0)

类似的东西:

with open('in.txt','r') as f:
    file = f.readlines()

for i in range(1,8,2):
    print file[i]

它会打印出来:

Yes, brave Sir Robin turned about

And gallantly he chickened out

Bravely talking to his feet

He beat a very brave retreat

答案 3 :(得分:0)

这就是我要做的,假设是Python 3.x:

with open("input.txt") as f:
    result = list(f)[1::2]

第一行打开文件,with语句将其放在上下文中。 在这种情况下(没有双关语)这意味着文件将自动关闭。 下一行获取文件列表,其中包含其中的所有行。 然后将列表切片,从位置1开始,每次跳过2个元素或行。 然后将其分配给变量结果。