replace_flag_names.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import sys
  2. import pathlib as pl
  3. import pandas as pd
  4. # run example
  5. # python replace_flag_names.py /Users/galizia/Documents/DATA/fidor_play/Or22a_GC6m /Users/galizia/Documents/Code/Git_code/pyview/view/flags_and_metadata_definitions/view_flags_renaming_2021.csv
  6. rename_directory = '/Users/galizia/Documents/DATA/fidor_play/Or22a_GC6m'
  7. rename_instructions = '/Users/galizia/Documents/Code/Git_code/pyview/view/flags_and_metadata_definitions/view_flags_renaming_2021.csv'
  8. def main(fle_or_dir, replacement_map_csv):
  9. map_df = pd.read_csv(replacement_map_csv)
  10. path = pl.Path(fle_or_dir)
  11. if path.is_file():
  12. files = [path]
  13. elif path.is_dir():
  14. files = path.rglob("*")
  15. else:
  16. raise FileNotFoundError(f"The specified path is neither a file nor a directory!\n{fle_or_dir}")
  17. for file in files:
  18. if file.is_file() \
  19. and file != pl.Path(replacement_map_csv) \
  20. and not file.name.startswith(".")\
  21. and str(file).find(".git") < 0:
  22. changes_made = False
  23. with open(file, "r+") as fh:
  24. try:
  25. s_read = fh.read()
  26. s = f"{s_read:s}"
  27. for ind, row in map_df.iterrows():
  28. s = s.replace(row["Old Flag Name"], row["Flag Name"])
  29. s = s.replace(row["Old Flag Subgroup"], row["Flag Subgroup"])
  30. if s != s_read:
  31. changes_made = True
  32. except UnicodeDecodeError as ucde:
  33. pass # happens if the file is not a text file encoded in unicode
  34. if changes_made:
  35. file.unlink()
  36. with open(file, "w") as fh:
  37. fh.write(s)
  38. if __name__ == '__main__':
  39. # assert len(sys.argv) == 3, \
  40. # f"Could not understand command. Please use as\n" \
  41. # f"python {__file__} <path to file or directory> <CSV file containing replacement map>"
  42. if len(sys.argv) == 3:
  43. main(sys.argv[1], sys.argv[2])
  44. else:
  45. main(rename_directory, rename_instructions)