Python Forum

Full Version: Python start from a specific string line and write?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to match a specific string and once match start writing the next line after after the matched string.

from output save in x variable I want to match "Current configuration" then write then start writing from next line.

Heres the sample output sting.

show run
Building configuration...

Current configuration : 1505 bytes
!
Content1
Content1
!
Content2
Content2
Once matched write but starting from next line. heres the target output.
!
Content1
Content1
!
Content2
Content2
Sample Configuration(but string the for line and not matching):
str = """show run
Building configuration...

Current configuration : 1505 bytes
!
Content1
Content1
!
Content2
Content2"""

with open('test.txt', 'w') as x:
    print str
    if "Current configuration" in str:
        x.writelines(itertools.islice(str, 4, None))
Thanks
It's never good idea to use built-ins as names in your code:

>>> str(12)
'12'
>>> str = 'something'
>>> str(12)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
From print statement I assume that Python 2.x is used. Is there any particular reason not to use Python 3?

Unfortunately I don't understand what you want to accomplish so no help here.

EDIT: it's tempting to think that now I understand what should be accomplished.

I see that itertools module is used and there is more suitable function: itertools.dropwhile()

from itertools import dropwhile

s = """show run
Building configuration...
 
Current configuration : 1505 bytes
!
Content1
Content1
!
Content2
Content2"""

iterator = dropwhile(lambda line: not line.startswith('Current'), s.split('\n')) 
next(iterator)
for line in iterator:
    print(line)
Output:
! Content1 Content1 ! Content2 Content2