cliTools.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """Collection of utilities for command-line interfaces and console scripts."""
  2. import os
  3. import re
  4. numberAddedRE = re.compile(r"#\d+$")
  5. def makeOutputFileName(
  6. input, outputDir=None, extension=None, overWrite=False, suffix=""
  7. ):
  8. """Generates a suitable file name for writing output.
  9. Often tools will want to take a file, do some kind of transformation to it,
  10. and write it out again. This function determines an appropriate name for the
  11. output file, through one or more of the following steps:
  12. - changing the output directory
  13. - appending suffix before file extension
  14. - replacing the file extension
  15. - suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid
  16. overwriting an existing file.
  17. Args:
  18. input: Name of input file.
  19. outputDir: Optionally, a new directory to write the file into.
  20. suffix: Optionally, a string suffix is appended to file name before
  21. the extension.
  22. extension: Optionally, a replacement for the current file extension.
  23. overWrite: Overwriting an existing file is permitted if true; if false
  24. and the proposed filename exists, a new name will be generated by
  25. adding an appropriate number suffix.
  26. Returns:
  27. str: Suitable output filename
  28. """
  29. dirName, fileName = os.path.split(input)
  30. fileName, ext = os.path.splitext(fileName)
  31. if outputDir:
  32. dirName = outputDir
  33. fileName = numberAddedRE.split(fileName)[0]
  34. if extension is None:
  35. extension = os.path.splitext(input)[1]
  36. output = os.path.join(dirName, fileName + suffix + extension)
  37. n = 1
  38. if not overWrite:
  39. while os.path.exists(output):
  40. output = os.path.join(
  41. dirName, fileName + suffix + "#" + repr(n) + extension
  42. )
  43. n += 1
  44. return output