[英]Print specific lines based on text in text-file in ||Python
我有一個包含大量文本的文本文件,但是我只想打印出特定的行/字符。 我怎么能這樣做?
示例文本文件
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
我只想打印包含edit
、 set action
和set comment
的行。
我多么想要
edit 29
set action relay xyz
set comment xyz
edit 30
set action relay abc
set comment acb
etc.
當前代碼:
# 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()
在換行符處拆分、過濾並在換行符處重新加入:
"\n".join(
line for line in contents.split("\n") if any(line.startswith(x) for x in ["Name:", "Type:", "Area:"])
)
您的文件在字符串contents
中的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.