如何保持行之间的缩进?
我正在用Python写一个新应用程序,我需要保持行与行之间的缩进。
我有一个文件里的代码:
line 1
__LINE TO CHANGE__
line 3
我想要得到的是:
line 1
added code line a
added code line b
line 3
我试过一些方法,比如添加\n、\n\r,使用""" """字符串,或者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()函数来更改一行。
谢谢
编辑:
我的代码:
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
如果你不知道用来缩进的具体字符是什么(比如空格、制表符等等),或者缩进用了多少个字符,那么你需要从你从文件中读取的原始行里获取这些信息,然后用这些信息来开头你新的一行。我将借用并补充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
0
另一个例子是关于HTML标签的,这里有三个部分需要从一个文件template.html中读取,并放入一个叫template的变量里。
<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)
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 检查。
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)
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
),那么你可能需要调整这个函数,让它能处理这些换行符。