validate_filename

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

Validate the filename and create a new filename with a suffix if the original exists.

If the file specified by file_pathname exists, this function generates a new filename by appending a suffix such as "(1)", "(2)", etc., to make it unique.

Parameters:
  • file_pathname (str) – Pathname of a file.

  • suffix_num (int) – Number to use as a suffix if the filename exists; defaults to 1.

Returns:

Validated file name (with a unique suffix if necessary).

Return type:

str

Examples:

>>> from pyhelpers.dirs import validate_filename
>>> import os
>>> test_file_pathname = "tests/data/test.txt"
>>> # When the file does not exist, return the same file name
>>> os.path.exists(test_file_pathname)
False
>>> file_pathname_0 = validate_filename(test_file_pathname)
>>> os.path.relpath(file_pathname_0)
'tests\data\test.txt'
>>> # Create a file named "test.txt"
>>> open(test_file_pathname, 'w').close()
>>> os.path.exists(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)
'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)
'tests\data\test(2).txt'
>>> # Remove the created files
>>> for x in [file_pathname_0, file_pathname_1]:
...     os.remove(x)