繁体   English   中英

在 ||Python 中根据文本文件中的文本打印特定行

[英]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 

我只想打印包含editset actionset 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.

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