utils.py 642 B

12345678910111213141516171819202122232425
  1. """
  2. utility functions for narps analysis
  3. """
  4. import os
  5. from datetime import datetime
  6. def log_to_file(
  7. fname, s, flush=False, add_timestamp=True, also_print=True, headspace=0
  8. ):
  9. """save string to log file"""
  10. if flush and os.path.exists(fname):
  11. os.remove(fname)
  12. if not isinstance(s, str):
  13. s = str(s)
  14. # add spacing before line
  15. if headspace > 0:
  16. s = os.linesep * headspace + s
  17. with open(fname, "a+") as f:
  18. if also_print:
  19. print(s)
  20. f.write(s + os.linesep)
  21. if flush and add_timestamp:
  22. f.write(datetime.isoformat(datetime.now()) + 2 * os.linesep)