Python2.7无法索引行,而是获取字母

2024-06-25 23:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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 我明白了

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

但我期待着第一次见面

dhcp 1 enabled

请让我知道我要做什么来解决这个问题


Tags: inforiflineenabledopenmyfilenum