我這種情況在一定的階級 -如何通過文件指針在Python
def f1(self, xxx):
do stuff with lines from file
def f0(self, filename):
with open(filename) as fp:
for lineContent in fp:
if re.match(lineContent):
do stuff with next 100+ lines from file
continue
else:
do other stuff while parsing lines
的問題:什麼是使用函數f1(...)的最好方法?
選項1:捕獲數組中的行直到出現標記,然後將此數組作爲f1()的xxx參數傳遞。
選項2:將f1()的代碼內容嵌入到f0()中。這也適用,但f0()變得非常大,難以閱讀。
尋找:某種方法用文件指針調用f1(),所以該方法可以讀取/處理行,觀察標記並在完成後將控制權返回給f0()。
Perl的等效代碼(我所期待的)將是:
sub f1 { ... }
sub f0 { ...
while (<$fp>) {
f1($fp) if /$re2match/;
continue with other stuff
}
}
感謝您幫助了新手pythonian。
謝謝。跟進ups-(1)您能否解釋zip(範圍(...))部分,因爲要處理的行的確切數量是未知的。什麼出來作爲_? (2)f0()中的for循環應該使用infile而不是fp? –
@ManidipSengupta:更新了我的答案。 (2)的好結果 - 我已經修復了我的代碼 – inspectorG4dget