蟒蛇2.7没有索引行,但得到的信,而不是
问题描述:
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
请让我知道我必须做的解决这个问题。
答
基于我的评论:
matched_lines =“\ n'.join(matched_lines)这将使从列表中选择一个字符串。不要这样做,你可以得到单独的线。
你如何生成'matched_lines'? – Marcin
'matched_lines'是一个列表还是元组? – Peaceful
你只有一行,如果你使用'[0]',它会返回第一个字符。 –