このようなファイルの内容がある場合:
old_string
-old_string
「old_string」のみを「+ new_string」に変更したいので、結果は次のようになります。
+new_string
-old_string
私のコードはこの結果を与えます:
+new_string
-+new_string
これは私のコードです:
with open(filename) as f:
s = f.read()
if old_string not in s:
return False
with open(filename, 'w') as f:
s = s.replace(old_string, new_string)
f.write(s)
return True
正規表現を試しましたが、正規表現を変数として渡すため機能しません。これは、これまでに行ったことです。
with open (filename, 'r' ) as f:
content = f.read()
content_new = re.sub('(\%old_string)', r'\new_string'%(old_string,new_string), content, flags = re.M)
これはあなたのために働くでしょう:-
import re
with open("output.txt", "a") as myfile:
with open('input.txt') as f:
lines = f.readlines()
for line in lines:
# print str(line)
ret = re.sub(r"(\s|^|$)old_string(\s|^|$)",r" +new_string ",line) #It will replace if line contain 'old_string' by '+new_string'
# print ret
myfile.write(ret+'\n')
注:-チェック output.txt
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加