import re
def replace_in_file(filepath, replacements):
"""
Replaces values in a file with a dictionary of replacements.
Supports older Python versions (Python 2 and 3).
"""
try:
with open(filepath, 'r') as f:
content = f.read()
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return False
# Use a regular expression for case-insensitive and whole-word replacement
pattern = re.compile(re.escape(list(replacements.keys())[0]), re.IGNORECASE)
for old, new in replacements.items():
content = pattern.sub(str(new), content) # Convert new to string to handle various types
try:
with open(filepath, 'w') as f:
f.write(content)
except Exception as e:
print(f"Error writing to file: {e}")
return False
return True
Add your comment