Python: 如果不在文件中添加新行,则保留现有行?

Python: Keep the existing line if not add a new line in a file?

如果现有值存在,我想保留现有行,否则将行添加到文件中。我正在为 nagios 主机文件编写脚本。

主机文件:

define host{
          use             hoststatus
          host_name       linuxhost1
          alias           linuxhost1
          hostgroups      linuxgroup
          Sev             1
}
define host{
          use             hoststatus
          host_name       linuxhost2
          alias           linuxhost2
          hostgroups      linuxgroup
          Sev             2
}
define host{
          use             hoststatus
          host_name       linuxhost3
          alias           linuxhost3
          hostgroups      linuxgroup
}

define host{
          use             hoststatus
          host_name       linuxhost4
          alias           linuxhost4
          hostgroups      linuxgroup
}

我写了这个脚本,如果该行不存在则添加该行(即最后两个主机中不存在 Sev 行,因此如果 Sev 则跳过它) 对于前两个主机,我不想添加任何内容。

代码:

import re,sys

with open(sys.argv[1],'r') as f1:
    data = f1.readlines()

txt=''

with open(sys.argv[1],'r') as f3:
    severity=True
    default=4
    vmowner=True
    default_VM = "XXXXXXXXXXXXXX"

    for line in f3:
        if line.strip().startswith('Sev'):
            severity=False

        if line.strip().startswith('Vmowner'):
            vmowner=False

    if severity:
        txt = txt + "\tSev\t\t" + str(default) + "\n"

    if vmowner:
        txt = txt + "\tVmowner\t\t" + str(default_VM) + "\n"
    txt = txt + "\tSevOwner\tYYYYYYYYYYYY\n"
    txt = txt + "}\n"

with open(sys.argv[1],'r+') as f2:
    for line in data:
        if line.strip().startswith('}'):
            line = line.replace('}',txt)
#        f2.write(line)
        print line,

但问题是我没有得到准确的输出。

生成的输出:

define host{
          use             hoststatus
          host_name       linuxhost1
          alias           linuxhost1
          hostgroups      linuxgroup
          Sev             1
        Vmowner         XXXXXXXXXXXXXX
        SevOwner        YYYYYYYYYYYY
}

define host{
          use             hoststatus
          host_name       linuxhost2
          alias           linuxhost2
          hostgroups      linuxgroup
          Sev             2
        Vmowner         XXXXXXXXXXXXXX
        SevOwner        YYYYYYYYYYYY
}

define host{
          use             hoststatus
          host_name       linuxhost3
          alias           linuxhost3
          hostgroups      linuxgroup
        Vmowner         XXXXXXXXXXXXXX
        SevOwner        YYYYYYYYYYYY
}


define host{
          use             hoststatus
          host_name       linuxhost4
          alias           linuxhost4
          hostgroups      linuxgroup
        Vmowner         XXXXXXXXXXXXXX
        SevOwner        YYYYYYYYYYYY
}

预期输出:

define host{
          use             hoststatus
          host_name       linuxhost1
          alias           linuxhost1
          hostgroups      linuxgroup
          Sev             1
        Vmowner         XXXXXXXXXXXXXX
        SevOwner        YYYYYYYYYYYY
}

define host{
          use             hoststatus
          host_name       linuxhost2
          alias           linuxhost2
          hostgroups      linuxgroup
          Sev             2
        Vmowner         XXXXXXXXXXXXXX
        SevOwner        YYYYYYYYYYYY
}

define host{
          use             hoststatus
          host_name       linuxhost3
          alias           linuxhost3
          hostgroups      linuxgroup
          Sev             4
          Vmowner         XXXXXXXXXXXXXX
          SevOwner        YYYYYYYYYYYY
}


define host{
          use             hoststatus
          host_name       linuxhost4
          alias           linuxhost4
          hostgroups      linuxgroup
          Sev             4
          Vmowner         XXXXXXXXXXXXXX
          SevOwner        YYYYYYYYYYYY
}

提前致谢。

您没有在每个主机之后将严重性标志重置为 true。这意味着第一台主机将标志设置为 false,然后永远无法输入后面检查标志的 if 语句。您需要添加逻辑来检查新主机文件的开头,以重置严重性标志等逻辑。

我会这样做:

  • 阅读整个文件
  • 将其分成块
  • 将每个块拆分成行
  • 添加任何需要的数据
  • 重新制作整个街区
  • 重新制作整个文件

from collections import OrderedDict

default_sev = 4
default_VM = "XXXXXXXXXXXXXX"
default_sevowner = "YYYYYYYYYYYY"

def add_missing(data_block):
    data_block = data_block.strip("}\n")
    lines = OrderedDict([line.split() for line in data_block.splitlines()])
    if "Sev" not in lines:
        lines["Sev"] = default_sev
    if "Vmowner" not in lines:
        lines["Vmowner"] = default_VM
    if "SevOwner" not in lines:
        lines["SevOwner"] = default_sevowner
    data = ""
    for key, value in lines.items():
        data += "          {: <16}{}\n".format(key, value)
    return "define host{{\n{}\n}}".format(data)

with open(sys.argv[1]) as f1:
    data = f1.read()

blocks = data.split('define host{') #split into blocks
blocks = filter(None, blocks) #remove empty blocks

with open(sys.argv[1], 'w') as f1:
    for block in blocks:
        f1.write(add_missing(block))