validate_filename

pyhelpers.dirs.validate_filename(file_path, suffix_num=1)[source]

Validate a filename, generating a uniquely suffixed name if the file already exists.

If the file specified by file_path already exists, this function appends a numeric suffix such as "(1)", "(2)", etc. to the filename (before its extension, if any) until it finds a pathname that doesn’t already exist. A pre-existing numeric suffix on file_path itself (e.g. from a prior call) is stripped before a new one is generated, so repeated calls don’t accumulate suffixes.

Parameters:
  • file_path (str | os.PathLike) – Pathname of a file.

  • suffix_num (int) – Starting number to use as a suffix if the filename already exists. Defaults to 1.

Returns:

Validated pathname of a file (with a unique numeric suffix if necessary).

Return type:

str

Examples:

>>> from pyhelpers.dirs import validate_filename
>>> import os

>>> test_file_pathname = "tests/data/test.txt"
>>> os.path.exists(test_file_pathname)
False

>>> # If the file does not exist, the function returns the same filename
>>> file_pathname_0 = validate_filename(test_file_pathname)
>>> os.path.relpath(file_pathname_0)  # on Windows
'tests\data\test.txt'

>>> # Create a file named "test.txt"
>>> open(test_file_pathname, 'w').close()
>>> os.path.isfile(test_file_pathname)
True

>>> # As "test.txt" exists, the function returns a new pathname ending with "test(1).txt"
>>> file_pathname_1 = validate_filename(test_file_pathname)
>>> os.path.relpath(file_pathname_1)  # on Windows
'tests\data\test(1).txt'

>>> # When "test(1).txt" exists, it returns a pathname of a file named "test(2).txt"
>>> open(file_pathname_1, 'w').close()
>>> os.path.exists(file_pathname_1)
True

>>> file_pathname_2 = validate_filename(test_file_pathname)
>>> os.path.relpath(file_pathname_2)  # on Windows
'tests\data\test(2).txt'

>>> # Remove the created files
>>> for x in [file_pathname_0, file_pathname_1]:
...     os.remove(x)