Python 尝试使用if语句修改文本文件

Python 尝试使用if语句修改文本文件,python,if-statement,Python,If Statement,我有一个正在读取的文本文件,根据特定条件修改特定行并将文件重写为新的文本文件。我现在的代码大部分都能工作,但是Python似乎忽略了elif语句中的一条,因为没有运行时错误。MWE如下所示: energy = .1 source = str('source x y z energy=%f' %energy) c = energy - 0.001 c_string = str("1010 %f %f" %(c, energy)) f = open("file.txt", "r+") with

我有一个正在读取的文本文件,根据特定条件修改特定行并将文件重写为新的文本文件。我现在的代码大部分都能工作,但是Python似乎忽略了
elif
语句中的一条,因为没有运行时错误。MWE如下所示:

energy = .1
source = str('source  x y z energy=%f' %energy)
c = energy - 0.001
c_string = str("1010 %f %f" %(c, energy))


f = open("file.txt", "r+")
with open ("newfiletxti", 'w') as n:
    d = f.readlines()
    for line in d:
        if not line.startswith("source"):
            if not line.startswith("xyz"):
                n.write(line)
        elif line.startswith("source"):
            n.write(source + "\n")
        elif line.startswith("xyz"):
            n.write(c_string + "\n")
    n.truncate()
    n.close()
守则:

elif line.startswith("source"):
    n.write(source + "\n")
如果文本文件中的行被标题为“source”的字符串替换,则按预期工作,但下一个块:

elif line.startswith("xyz"):
    n.write(c_string + "\n")

没有效果。新文本文件只是缺少以xyz开头的行。我猜我的多个
elif
语句的语法不正确,但我不确定原因。

如果
块像这样,请尝试

    if line.startswith("source"):
        n.write(source + "\n")
    elif line.startswith("xyz"):
        n.write(c_string + "\n")
    else:
        n.write(line)

第三个elif永远不会达到。以下是为清晰起见而简化的代码:

if not line.startswith("source"):
# suff
elif line.startswith("xyz"):
# stuff

以“xyz”开头的内容不是以“source”开头的。

第一个
if
elif
处理所有情况——要么行以
source
开头,要么行不以
开头。我认为您需要将第一个
if
及其嵌套的
if
组合成一个条件:

if not line.startswith("source") and not line.startswith("xyz"):
    n.write(line)
或同等的(通过):

或者,您可以通过重新排序您的条件使其更清晰:

if line.startswith("source"):
    n.write(source + "\n")
elif line.startswith("xyz"):
    n.write(c_string + "\n")
else:
    n.write(line)

如果不是line.startswith(“source”)
在一行以
xyz
开头时被触发,因此最后一个
elif
永远不会执行。从最具体到最一般的顺序排列您的条件。要添加到最后一条注释,为什么不以else结尾?对于第一条注释,所讨论的行是最后一条
elif
,而不是嵌套的。对于第二行,可能还有其他行不需要受影响?此外,Bogdan,您不需要执行
n.close()
with块会处理这个问题。如果我理解正确,我需要重新构造初始的“If not”语句。类似于
if not line.startswith(“this”或“this”)
然后执行此操作
如果执行此操作
如果执行此操作,则执行此操作
与我现在使用的嵌套if语句相反?不幸的是,这不起作用,但原因在下面的答案中,脚本永远不会到达最后一个else语句,所以不管是else还是elif:(谢谢,我相信这最能描述它)。
if line.startswith("source"):
    n.write(source + "\n")
elif line.startswith("xyz"):
    n.write(c_string + "\n")
else:
    n.write(line)