2016-09-22 68 views
0

我有以下的代碼工作,但現在我想在最後添加一個行數。Python的行數輸出

print "Looking for abc" 
for line1 in open("file.txt"): 
    if "abc" in line1: 
     print line1, 

我可以把它打印出來當然很好,但無法弄清楚如何獲得最後一行數?

+1

'數+ = 1'在循環和'print(count)'結尾。 –

+0

謝謝..有沒有辦法讓最後的總數與每一行獲取數字? – Jay

回答

0

如果你想用一個計數器來做到這一點,你可以編輯你是

print "Looking for abc" 
count = 0 
for line1 in open("file.txt"): 
    if "abc" in line1: 
     print line1, 
     count += 1 
print count 

或者,如果你想要一個更Python的方式,你可以說

lines = [line for line in open('file.txt') if 'abc' in line] 
for line in lines: 
    print line, 
print len(lines)