• 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):
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    - replacing the file extension
18    - suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid
19      overwriting an existing file.
20
21    Args:
22        input: Name of input file.
23        outputDir: Optionally, a new directory to write the file into.
24        extension: Optionally, a replacement for the current file extension.
25        overWrite: Overwriting an existing file is permitted if true; if false
26            and the proposed filename exists, a new name will be generated by
27            adding an appropriate number suffix.
28
29    Returns:
30        str: Suitable output filename
31    """
32    dirName, fileName = os.path.split(input)
33    fileName, ext = os.path.splitext(fileName)
34    if outputDir:
35        dirName = outputDir
36    fileName = numberAddedRE.split(fileName)[0]
37    if extension is None:
38        extension = os.path.splitext(input)[1]
39    output = os.path.join(dirName, fileName + extension)
40    n = 1
41    if not overWrite:
42        while os.path.exists(output):
43            output = os.path.join(
44                dirName, fileName + "#" + repr(n) + extension)
45            n += 1
46    return output
47