Python 如何保持行与行之间的缩进?

Python 如何保持行与行之间的缩进?,python,Python,我正在用python编写一个新的应用程序,我需要保持行与行之间的缩进 我有一个文件中的代码: line 1 __LINE TO CHANGE__ line 3 我想得到: line 1 added code line a added code line b line 3 我尝试了一些解决方案,添加了\n\n\r,usign“”“”字符串,string(“”),但我只得到了这两个结果: line 1 added code line a added code line

我正在用python编写一个新的应用程序,我需要保持行与行之间的缩进

我有一个文件中的代码:

line 1
   __LINE TO CHANGE__
line 3
我想得到:

line 1
   added code line a
   added code line b
line 3
我尝试了一些解决方案,添加了\n\n\r,usign“”“”字符串,string(“”),但我只得到了这两个结果:

line 1
    added code line a added code line b
line 3


line 1
    added code line a
added code line b
line 3
我正在使用replace()函数更改一行

谢谢

编辑: 我的代码:

“添加了代码行a\n添加了代码行b\n”
写入两行缩进四个空格

要基于某些条件进行替换,请使用枚举和if检查:

with open("in.txt") as f:
    lines = f.readlines()
    for ind, line in enumerate(lines):
        if "whatever" in line:
           lines[ind] = "   added code line a\n   added code line b\n"
    with open("in.txt","w") as f1:
        f1.writelines(lines)
您可以这样使用它:

code = '''line 1
    __LINE TO CHANGE__
line 3'''

print('\n'.join(replace_line(
    code.split('\n'),                           # one string per line
    '__LINE TO CHANGE__',                       # the string to replace
    ["added code line a", "added code line b"]  # the strings to replace with
)))
输出:

line 1
    added code line a
    added code line b
line 3
您也可以将其用于文件,方法如下:

with open("input") as f:
    print(''.join(replace_line(f, 'some pattern\n', ['foo\n', 'bar\n'])))

请注意,这里我在模式和替换的末尾添加了一个
'\n'
。如果您打算将其用于
读取行
(每行末尾包含一个
\n
)的输出,那么您可能需要调整函数以期望它们并为您执行此操作。

另一个带有html标记的示例,用于更改从文件template.html读取并放入模板变量的3个部分

<div>
   <div>
        ___MENU___
    </div>
</div>
<div>
    ___CONTENT___
</div>
<div>
    ___BOTTOM___
</div>

template=template.replace(可用,文本添加)

如果您不知道缩进时使用的特定字符(空格、制表符等)或缩进时使用的字符数,则需要从文件中读取的原始行中获取该字符,然后在新行之前使用该字符。我将借用并补充Padraic的回复:

with open("file.txt") as f:
    lines = f.readlines()
    for ind, line in enumerate(lines):
        num_of_chars = len(line) - len(line.lstrip()) # Get the preceding characters.
        new_line = line[:num_of_chars] + "added code line a" # Add the same to the new line.
        lines[ind] = new_line

那么你的代码在哪里?你的意思是像用反斜杠扩展一行代码一样吗?
“foo”。替换(“foo”,“foo+”)
@paganu将你的代码添加到问题正文中!所以你想用两行新行替换第2行?是的,但我不知道总是缩进和在哪里找到确切的行。Well只是在行上枚举,如果要替换的行是一行,则使用索引替换它,然后使用WriteEyes,但可能更复杂,我发布了一个例子,你必须知道你想要更改哪些行,或者至少是索引,所以发布的代码会给你预期的输出,因此很难再这样做了。你的函数匹配缩进并替换它,这是我一直在寻找的
with open("input") as f:
    print(''.join(replace_line(f, 'some pattern\n', ['foo\n', 'bar\n'])))
<div>
   <div>
        ___MENU___
    </div>
</div>
<div>
    ___CONTENT___
</div>
<div>
    ___BOTTOM___
</div>
html = "<p>"
hrml += "   HELLO WORLD"   
html += "</p>"
available_pos = ["___MENU___", "___CONTENT___", "___BOTTOM___"]
text_to_add = [html, html1, html2]
with open("file.txt") as f:
    lines = f.readlines()
    for ind, line in enumerate(lines):
        num_of_chars = len(line) - len(line.lstrip()) # Get the preceding characters.
        new_line = line[:num_of_chars] + "added code line a" # Add the same to the new line.
        lines[ind] = new_line