私は、指定された単語で始まる行があるかどうかを調べるコードを持っています。ただし、行がスペースでインデントされていると、一部の行では機能しません。テキストを直接読み込み、スペースを無視する方法はありますか?ここで テキストの前にスペースがあるテキストを検索して置き換える方法は?
はコードです: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