outpututils.py 1.0 KB

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