2017-07-07 47 views
1

我這種情況在一定的階級 -如何通過文件指針在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。

回答

0
def f1(self, filepointer): 
    for _, line in zip(range(100), filepointer): 
     # do stuff with the line 


def f0(self, filename): 
    with open(filename) as infile: 
     for lineContent in infile: 
      if re.match(lineContent): 
       f1(infile) # only works because of the way file iterators are set up. Otherwise, that for-loop's scoping iterator will bork you here 
       # that continue is unnecessary here 
      else: 
       # do other stuff while parsing lines 

UPDATE:澄清基於評論

zip是一個函數,它的多個iterables(如列表,文件,詞典等),並返回的元組的單個迭代,其中,第i個每個元組的元素來自輸入到zip的第i個迭代。 zip也會在最小的可迭代元素耗盡時終止。因此,檢查了這一點:

In [14]: for t in zip('asdf', '1234'): print(t) 

('a', '1') 
('s', '2') 
('d', '3') 
('f', '4') 

In [15]: for t in zip('asdf', '123'): print(t) 
('a', '1') 
('s', '2') 
('d', '3') 

既然你問處理下一個100行,range(100)似乎是理想的工具。 for _, line in ...類似於說for a, line in ...,它只是用下劃線表示我們不想跟蹤的變量(嘗試print ing _以查看在該循環的每次迭代中它的值是什麼)。
如果您不知道要處理多少行的確切數量,這對您來說是一個錯誤的解決方案。

+0

謝謝。跟進ups-(1)您能否解釋zip(範圍(...))部分,因爲要處理的行的確切數量是未知的。什麼出來作爲_? (2)f0()中的for循環應該使用infile而不是fp? –

+0

@ManidipSengupta:更新了我的答案。 (2)的好結果 - 我已經修復了我的代碼 – inspectorG4dget