2017-01-13 11:16:01 +00:00
|
|
|
"""Collection of utilities for command-line interfaces and console scripts."""
|
2024-02-06 15:47:35 +02:00
|
|
|
|
2017-01-13 11:16:01 +00:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
|
|
|
|
|
2019-04-01 13:53:59 -07:00
|
|
|
numberAddedRE = re.compile(r"#\d+$")
|
2017-01-13 11:16:01 +00:00
|
|
|
|
|
|
|
|
2022-08-22 06:26:30 -06:00
|
|
|
def makeOutputFileName(
|
|
|
|
input, outputDir=None, extension=None, overWrite=False, suffix=""
|
|
|
|
):
|
2020-05-19 09:51:17 +01:00
|
|
|
"""Generates a suitable file name for writing output.
|
|
|
|
|
|
|
|
Often tools will want to take a file, do some kind of transformation to it,
|
|
|
|
and write it out again. This function determines an appropriate name for the
|
|
|
|
output file, through one or more of the following steps:
|
|
|
|
|
|
|
|
- changing the output directory
|
2022-08-22 06:26:30 -06:00
|
|
|
- appending suffix before file extension
|
2020-05-19 09:51:17 +01:00
|
|
|
- replacing the file extension
|
|
|
|
- suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid
|
|
|
|
overwriting an existing file.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
input: Name of input file.
|
|
|
|
outputDir: Optionally, a new directory to write the file into.
|
2022-08-22 06:26:30 -06:00
|
|
|
suffix: Optionally, a string suffix is appended to file name before
|
2022-08-19 12:20:21 -06:00
|
|
|
the extension.
|
2020-05-19 09:51:17 +01:00
|
|
|
extension: Optionally, a replacement for the current file extension.
|
|
|
|
overWrite: Overwriting an existing file is permitted if true; if false
|
|
|
|
and the proposed filename exists, a new name will be generated by
|
|
|
|
adding an appropriate number suffix.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: Suitable output filename
|
|
|
|
"""
|
2017-01-13 11:16:01 +00:00
|
|
|
dirName, fileName = os.path.split(input)
|
|
|
|
fileName, ext = os.path.splitext(fileName)
|
|
|
|
if outputDir:
|
|
|
|
dirName = outputDir
|
|
|
|
fileName = numberAddedRE.split(fileName)[0]
|
|
|
|
if extension is None:
|
|
|
|
extension = os.path.splitext(input)[1]
|
2022-08-22 06:26:30 -06:00
|
|
|
output = os.path.join(dirName, fileName + suffix + extension)
|
2017-01-13 11:16:01 +00:00
|
|
|
n = 1
|
|
|
|
if not overWrite:
|
|
|
|
while os.path.exists(output):
|
|
|
|
output = os.path.join(
|
2022-08-22 06:26:30 -06:00
|
|
|
dirName, fileName + suffix + "#" + repr(n) + extension
|
|
|
|
)
|
2017-01-13 11:16:01 +00:00
|
|
|
n += 1
|
|
|
|
return output
|