validate_filename

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

If the filename exist, then create new filename with a suffix such as “(1)”, “(2)”, and so on.

Parameters:
  • file_pathname (str) – pathname of a file

  • suffix_num (int) – a number as a suffix appended to the filename, defaults to 1

Returns:

a validated file name

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, the function 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)