Gajendra D Ambi Gajendra D Ambi - 28 days ago 6
Python Question

python 2.7 fails to index line but gets letter instead

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


When i do
print matched_lines

I get

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


but if i try to index a line

print matched_lines[0]


i get

d


but i am expecting the first ine

dhcp 1 enabled


Please let me know what do I have to do fix this.

Answer

Based on my comment:

matched_lines = '\n'.join(matched_lines) this will make one string from your list. Dont do this, and you can get individual lines.