首页 > 解决方案 > Python如何在使用with..for线模式时在行尾连接文本

问题描述

我有一个代码试图在行尾连接行号,使用“with..for line”模式

我的代码是:

with open(tmp_filename,'a+') as file:
    for line in open(out_filename):
        if "pattern" in line:
            mark_enum = 0
        if mark_enum > -1 and "{" in line:
            continue
        if mark_enum > -1 and "}" in line:
            break
        if mark_enum > -1 and not line.isspace():
            line += " = " + str(mark_enum)
            file.write(line)
            mark_enum += 1

结果:

 = 0    LINE A
 = 1    LINE B
 = 2    LINE C

而不是必需的:

LINE A = 0
LINE B = 1
LINE C = 2

请建议我的错误是什么以及如何解决它

标签: python

解决方案


推荐阅读