【发布时间】:2012-02-16 04:18:36
【问题描述】:
我有一个代码可以搜索一行是否以指定的单词开头,如果是,它会使用指定的输入更改整行。但是,如果行由空格缩进,它对某些行不起作用?有没有办法直接阅读文本并忽略空格。
这是代码:(用 cmets 说明问题所在)
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()
谢谢
编辑:我想保留原始文件中存在的所有空格,即使在我修改的行中也是如此。
【问题讨论】:
标签: python search replace spaces