[英]Print specific lines based on text in text-file in ||Python
I have a text file that contains lots of text however, I only want specific lines/characters printed out.我有一个包含大量文本的文本文件,但是我只想打印出特定的行/字符。 How can do I this?
我怎么能这样做?
Example Text-file示例文本文件
edit 29
set status enable
set sender-pattern-type default
set sender-pattern *
set recipient-pattern-type default
set recipient-pattern *
set sender-ip-type ip-group
set sender-ip-group
set reverse-dns-pattern *
set reverse-dns-pattern-regexp no
set authenticated any
unset tls-profile
set action relay
set comment
I want to print only lines that contain edit
, set action
and set comment
.我只想打印包含
edit
、 set action
和set comment
的行。
How I want it我多么想要
edit 29
set action relay xyz
set comment xyz
edit 30
set action relay abc
set comment acb
etc.
Current code:当前代码:
# Save results of command in "Output" while splitting one whole output line into multiple lines (original output).
output = "".join(ssh_stdout.readlines())
# Save SSH output to a text-file.
file = open('outputFortimail.txt', "w")
file.write(output)
file.close()
file.write("\n".join(
line for line in file.split("\n") if any(line.startswith(x)
for x in
["edit:", "set sender-ip-mask:", "set comment:", "unset comment"])))
file.close()
Split on newline, filter, and join back on newline:在换行符处拆分、过滤并在换行符处重新加入:
"\n".join(
line for line in contents.split("\n") if any(line.startswith(x) for x in ["Name:", "Type:", "Area:"])
)
Where your file is in the string contents
.您的文件在字符串
contents
中的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.