1. import re
  2. def replace_in_file(filepath, replacements):
  3. """
  4. Replaces values in a file with a dictionary of replacements.
  5. Supports older Python versions (Python 2 and 3).
  6. """
  7. try:
  8. with open(filepath, 'r') as f:
  9. content = f.read()
  10. except FileNotFoundError:
  11. print(f"Error: File not found at {filepath}")
  12. return False
  13. # Use a regular expression for case-insensitive and whole-word replacement
  14. pattern = re.compile(re.escape(list(replacements.keys())[0]), re.IGNORECASE)
  15. for old, new in replacements.items():
  16. content = pattern.sub(str(new), content) # Convert new to string to handle various types
  17. try:
  18. with open(filepath, 'w') as f:
  19. f.write(content)
  20. except Exception as e:
  21. print(f"Error writing to file: {e}")
  22. return False
  23. return True

Add your comment