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