簡體   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