[英]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.从输出保存在 x 变量中我想匹配“当前配置”然后写入然后从下一行开始写入。
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):示例配置(但字符串 for 行且不匹配):
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 . itertools.islice
工作在一个字符串的字符,而不是行。 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.我会将文本分成几行,然后使用带有
enumerate()
for
循环来查找带有文本的行。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.