![]() |
Python start from a specific string line and write? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Python start from a specific string line and write? (/thread-19411.html) |
Python start from a specific string line and write? - searching1 - Jun-27-2019 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 Content2Once matched write but starting from next line. heres the target output. ! Content1 Content1 ! Content2 Content2Sample 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 RE: Python start from a specific string line and write? - perfringo - Jun-27-2019 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 callableFrom 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)
|