我有一个代码,用于搜索一行是否以指定的单词开头,如果是,则会用指定的输入更改整行。但是,如果行由空格缩进,它对某些行不起作用?有没有办法直接阅读文本并忽略空格。如何搜索并替换文本之前有空格的文本?
下面是代码:(与问题出在哪里评论)
import os
def template(filein):
currdir = os.getcwd() # get current directory
new_file = open(os.path.join(currdir,'maindir','template.in'),'wt')
old_file = open(filein)
for line in old_file:
if line.startswith(' indent'):
# this part works well because I put the exact number of spaces present in the text before the search word
new_file.write(' indent == %s \n' % str('%(indent)s'))
elif line.startswith('noindent'):
# this part can't find noindent because i didn't specify the spaces before that that is present in the text
new_file.write('noindent == %s \n' % str('%(noindent)s'))
else:
new_file.write(line)
new_file.close()
old_file.close()
感谢
编辑:我想保留所有存在于原始文件的空间,即使在线路是我修改了。
我试过,但它消除左边的,我不希望更改线路的所有空间。我也想保留原来的空格后,我已经改变了线。谢谢 – mikeP
@mikeP:然后,您可以将其存储在其他变量中,而不是替换该行,并检查该行。我会编辑答案。 –
我尝试了修改,但是我更改的行上的缩进仍然消失。即使在我更改的行中,我也想保留原始缩进。谢谢。 – mikeP