在Python中,我們可以通過線在文件中的行進行迭代。但是如果我想通過兩行迭代呢?
f = open("filename")
for line1, line2 in ?? f ??:
do_stuff(line1, line2)
在Python中,我們可以通過線在文件中的行進行迭代。但是如果我想通過兩行迭代呢?
f = open("filename")
for line1, line2 in ?? f ??:
do_stuff(line1, line2)
你可以做這樣的事情:
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
的解決方案可能更好地避免這種需求。
f = open("file")
content = f.readlines()
print content[0] #You can choose lines from a list.
print content[1]
這是做這件事。現在,您可以使用for循環遍歷列表,並根據需要執行任何操作,或者明確地選擇行。
使用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.
這會將整個文件一次讀入內存。這可能不是一個好主意。 –