outpututils.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # Various utility functions for generating output files and directories.
  2. from io import open
  3. from os import makedirs
  4. from os.path import dirname, isdir, isfile
  5. def createDirFor(filePath):
  6. '''Creates an output directory for containing the given file path.
  7. Nothing happens if the directory already exsits.
  8. '''
  9. dirPath = dirname(filePath)
  10. if dirPath and not isdir(dirPath):
  11. makedirs(dirPath)
  12. def rewriteIfChanged(path, lines):
  13. '''Writes the file with the given path if it does not exist yet or if its
  14. contents should change. The contents are given by the "lines" sequence.
  15. Returns True if the file was (re)written, False otherwise.
  16. '''
  17. newLines = [line + '\n' for line in lines]
  18. if isfile(path):
  19. with open(path, 'r', encoding='utf-8') as inp:
  20. oldLines = inp.readlines()
  21. if newLines == oldLines:
  22. print('Up to date: %s' % path)
  23. return False
  24. else:
  25. print('Updating %s...' % path)
  26. else:
  27. print('Creating %s...' % path)
  28. createDirFor(path)
  29. with open(path, 'w', encoding='utf-8') as out:
  30. out.writelines(newLines)
  31. return True