2016-11-11 68 views
1
fromStr = 'start of show feature' 
toString = 'end of show feature' 

with open(filepath) as myFile: 
    for num, line in enumerate(myFile, 1): 
     if fromStr in line: 
      fromline = num 

with open(filepath) as myFile: 
    for num, line in enumerate(myFile, 1): 
     if toString in line: 
      toline = num 

fromline = fromline+1 

f = open(filepath) 
lines=f.readlines() 
store = lines[fromline:toline-1] 
store1 = '\n'.join(store) 
text = "\n".join([ll.rstrip() for ll in store1.splitlines() if ll.strip()]) # remove blank lines 

string = 'enabled' 

matched_lines = [line for line in text.split('\n') if string in line] #get matched lines 
#matched_lines = list(set(matched_lines)) #get unique items only or remove duplicates (the result will be unordered for many items) 
matched_lines = '\n'.join(matched_lines) #rearrange the lines in order 

當我做 print matched_lines 我得到蟒蛇2.7沒有索引行,但得到的信,而不是

dhcp 1 enabled hsrp_engine 1 enabled interface-vlan 1 enabled lacp 1 enabled ntp 1 enabled scpServer 1 enabled sshServer 1 enabled vpc 1 enabled

,但如果我嘗試爲線

print matched_lines[0]

我得到

d

,但我希望第一個INE

dhcp 1 enabled

請讓我知道我必須做的解決這個問題。

+0

你如何生成'matched_lines'? – Marcin

+0

'matched_lines'是一個列表還是元組? – Peaceful

+0

你只有一行,如果你使用'[0]',它會返回第一個字符。 –

回答

2

基於我的評論:

matched_lines =「\ n'.join(matched_lines)這將使從列表中選擇一個字符串。不要這樣做,你可以得到單獨的線。