I have a code that search if a line begin with a specified word and if it does, it changes that whole line with a specified input. However, it doesn’t work for some lines if the line is indented by spaces? Is there a way to read the text directly and ignore the spaces.
Here is the code: (with comments on where the problem is)
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()
Thanks
EDIT: I want to preserve all the spaces present in the original file, even in the lines that I modified.
You can use
lstripto remove the whitespace from the beginning (left) of a line:On a sidenote, I recommend using
with open('filename') as new_file, instead of what you’re doing now. This creates a block in which the file is available and makes sure the file is closed at the end of the block. See the end of this section in the docs.