2013-07-28 50 views
-6

所以,我需要一個代碼來從txt文件讀取偶數行。 這是一個任務的例子。Python。文本文件中的偶數行

輸入:

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 
+2

那麼,什麼問題?開始[這裏](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)。 –

回答

2

所以,只輸出偶數行。

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

您可以迭代文件對象本身,而不是使用'file.readlines'將所有行加載到內存中,其次使用'enumerate'而不是手動建立索引。 –

+0

@AshwiniChaudhary是的。 Thx爲您的評論。 – MarshalSHI

+0

'如果我%2 = 0'會引發'SyntaxError'。 –

3

使用itertools.islice

import itertools 
import sys 

with open('input.txt') as f: 
    sys.stdout.writelines(itertools.islice(f, 1, None, 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 
0

這是我會怎麼做,假設Python 3.x都有:

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

第一行打開文件時,用的語句把它在上下文。 在這種情況下(沒有雙關語意思)這意味着文件將自動關閉。 下一行獲取文件列表,其中包含所有行。 然後將列表切片,從位置1開始,每次跳躍2個元素或線條。 然後將其分配給變量結果。

+0

如果該文件有10億行?您正在將所有行存儲在內存中。 –

+0

然後我會使用itertools.islice,就像在上面的答案中一樣,但是這會更復雜,很可能包含比我的答案更多的新概念,我認爲我只是簡單而簡潔。 – rlms