为什么 python 在替换一行时删除给定文件中的每一行?

Why is python removing each line in the given file when replacing one line?

我有一个配置文件,我想用我的变量 ipaddr

中存储的值替换以 IPADDR=someIP 开头的行

我的代码:

for line in fileinput.input(["/etc/sysconfig/network-scripts/ifcfg-ens192"], inplace=True):
    if line.strip().startswith('IPADDR='):
        line ="IPADDR="+ipaddr
        sys.stdout.write(str((line)) + "\n")

它确实正确设置了我想要的行,但也删除了每一行,但它应该只删除空行,为什么不保留其他现有行?

感谢

一切都很好,除了您没有编写不以 'IPADDR' 开头的文件的其余部分,只需添加该行,一切都应该很好。

for line in fileinput.input(["/etc/sysconfig/network-scripts/ifcfg-ens192"], inplace=True):
    if line.strip().startswith('IPADDR='):
        line ="IPADDR="+ipaddr
        sys.stdout.write(str((line)) + "\n")
    elif len(line.strip()) > 0: # add this and below line
        sys.stdout.write(line) + "\n")

您应该 write line 所有行:

for line in fileinput.input(["/etc/sysconfig/network-scripts/ifcfg-ens192"], 
                            inplace=True):
    if line.strip().startswith('IPADDR='):
        line ="IPADDR="+ipaddr
    sys.stdout.write(str((line)) + "\n")  #<-- here, indentation

要跳过空白行,一种方法可能是:

    ...
    stripped = line.strip()
    is_not_blank = bool( stripped )
    startswithIPADDR = not is_blank and stripped.startswith('IPADDR=')
    if is_not_blank:
        if startswithIPADDR:
            line ="IPADDR="+ipaddr
        sys.stdout.write(str((line)) + "\n")  #<-- here, indentation

终于解决了它:

for line in fileinput.input(["/etc/sysconfig/network-scripts/ifcfg-ens192"], inplace=True):
    if line.strip().startswith('IPADDR='):
        line ="IPADDR="+ipaddr
        sys.stdout.write(str((line)) + "\n")
    elif len(line.strip()) > 0:
        sys.stdout.write(str((line) + "\n"))
for line in fileinput.input(["/etc/sysconfig/network-scripts/ifcfg-ens192"], inplace=True):
        line = line.strip()
        if line == '': continue
        print line

非常感谢你们!