2011-10-30 27 views

回答

2

你可以做這樣的事情:

with open('myFile.txt') as fh: 
    for line1 in fh: 
    line2 = next(fh) 

    # Code here can use line1 and line2. 

您可能需要在呼叫StopIteration錯誤觀賞到next(fh)如果你有奇線。 izip_longest的解決方案可能更好地避免這種需求。

1
f = open("file") 
content = f.readlines() 
print content[0] #You can choose lines from a list. 
print content[1] 

這是做這件事。現在,您可以使用for循環遍歷列表,並根據需要執行任何操作,或者明確地選擇行。

+1

這會將整個文件一次讀入內存。這可能不是一個好主意。 –

5

使用itertools recipes中的grouper函數。

from itertools import zip_longest 

def grouper(n, iterable, fillvalue=None): 
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return zip_longest(fillvalue=fillvalue, *args) 


f = open(filename) 
for line1, line2 in grouper(2, f): 
    print('A:', line1, 'B:', line2) 

使用zip代替zip_longest忽略在端部的奇數行。

zip_longest函數在Python命名爲izip_longest 2.