INNER CODE UNIT · Python
replace_string_in_file
sameerasw/essentials · scripts/fix_translations.py:78
def replace_string_in_file(file_path, key, new_val):
if not os.path.exists(file_path):
return False
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Pattern matches <string name="key"[^>]*>.*?</string>
pattern = re.compile(rf'(<string\s+name="{re.escape(key)}"[^>]*>)(.*?)(</string>)', re.DOTALL)
match = pattern.search(content)
if not match:
return False
old_val = match.group(2)
if old_val == new_val:
return False
new_content = pattern.sub(rf'\g<1>{new_val}\g<3>', content)
with open(file_path, "w", encoding="utf-8") as f: