Python文件對象是一個迭代,你可以要求它的下一行,而循環:
with open(inputfilename) as ifh:
for line in ifh:
if line.startswith('for(') and line.endswith(';\n'):
line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh)
它使用next()
function從ifh
文件對象中檢索接下來的兩項並將它們添加到當前行。之後的外部循環將繼續執行。
爲了說明,看看這個迭代循環的輸出:
>>> lst = [1, 2, 3, 4]
>>> lst_iter = iter(lst)
>>> for i in lst_iter:
... print i
... if i == 2:
... print 'skipping ahead to', next(lst_iter)
...
1
2
skipping ahead to 3
4
這裏next()
先進lst_iter
迭代到下一個項目,然後將外循環for
與之後的下一個值繼續進行。
您的下一個問題是原地重寫文件;您無法同時讀取和寫入同一個文件,並希望只替換正確的部分。緩衝和不同的線路長度會妨礙您的發展。
使用fileinput
module處理替換文件的內容:
import sys
import fileinput
for line in fileinput.input(inputfilename):
if line.startswith('for(') and line.endswith(';'):
line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh)
sys.stdout.write(line)
或使用我in-place file rewriting context manager。
from inplace import inplace
with inplace(inputfilename) as (ifh, ofh):
for line in ifh:
if line.startswith('for(') and line.endswith(';'):
line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh)
ofh.write(line)
我想這就是我正在尋找的。 – TheRookierLearner
ifh.next()'是否有'next(ifh)'這個選項?或者它們是否相同? – crennie
@crennie:在Python 3中,'.next()'被重命名爲'.__ next __()'。該函數正確處理任一方法。 'next()'函數也可以給你一個默認值。 –