如何在行之间保留缩进?

时间:2014-10-31 20:47:44

标签: 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,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()函数来改变一行。

由于

EDITED: 我的代码:

Reading from file and put into variable named code:
line 1
    __LINE TO CHANGE__
line 3

text = "added code line a"
text += "added code line b" 

available_pos = ["__LINE TO CHANGE__"]
text_to_add = [text]

code = code.replace(available_pos, text_to_add)

4 个答案:

答案 0 :(得分:0)

with open("in.txt") as f:
    lines = f.readlines() # get all lines
    lines[1] = "    added code line a\n    added code line b\n" #reassign second line in lines 
    with open("in.txt","w") as f1: # overwrite the file with updated content
        f1.writelines(lines)

" added code line a\n added code line b\n"写两行缩进四个空格

要根据特定条件进行替换,请使用enumerate和if check:

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)

答案 1 :(得分:0)

import re

INDENT_RE = re.compile(r'^\s*$')

def matching_indent(line, pattern):
    """
    Returns indent if line matches pattern, else returns None.
    """
    if line.endswith(pattern):
        indent = line[:-len(pattern)]
        if INDENT_RE.match(indent):
            return indent
    return None

def replace_line(lines, pattern, replacements):
    for line in lines:
        indent = matching_indent(line, pattern)
        if indent is None:
            yield line
        else:
            for replacement in replacements:
                yield indent + replacement

你可以像这样使用它:

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'。如果您打算使用readlines的输出(在每行的末尾包含\n),那么您可能需要调整函数以期望它们并为您执行此操作。

答案 2 :(得分:0)

另一个使用html标签的示例,3个部分用于更改从文件template.html读取并放入模板var

<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]

template = template.replace(available_pos,text_to_add)

答案 3 :(得分:0)

如果您不知道用于缩进的特定字符(空格,制表符等等)或用于缩进的数量,那么您需要从您从中读取的原始行中获取该字符该文件,然后使用它在您的新行之前。我要去借用&amp;加入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