简体   繁体   中英

Python start from a specific string line and write?

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))

itertools.islice works on characters of a string, not lines . So you'll need to break up your text into lines:

x.write("\n".join(itertools.islice(str.split("\n"), 4, None)))

I would split text into lines and then use for loop with enumerate() to find line with text. After then I would write rest of text.

text = """show run
Building configuration...

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

lines = text.split('\n')

for number, line in enumerate(lines): # get line and its number
    if "Current configuration" in line:
        print(number, '>', line)

        rest_text = '\n'.join(lines[idx+1:]) # join lines in one text

        with open('test.txt', 'w') as x:
            x.write(rest_text)
            break  # exit `for` loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM