Created
September 22, 2021 03:24
-
-
Save M49ICKPIxi3/94ad90406b71a4497d2c3da1d239be47 to your computer and use it in GitHub Desktop.
Creates a non-horrible-looking unique filename that's checked to not exist, easily editable to taste. Modification of this response https://stackoverflow.com/a/15746092/6194588
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from random import sample | |
from string import digits, ascii_uppercase, ascii_lowercase | |
# Checking the directory itself needs to be done prior to invocation, something like this would work depending on use | |
# if not os.path.exists(output_dir): os.mkdir(output_dir) | |
def unique_filename(output_dir, name, suffix='.txt', length=8): | |
break_recursion = 100 # just in case... | |
def unique_filename_4sure(_length, _break_recursion): | |
if break_recursion <= 0: | |
print('Err: [infinite recursion] something seriously messed up... ') | |
return f'{output_dir}ERROR.txt' | |
chars = ascii_lowercase + ascii_uppercase + digits | |
rand_part = ''.join(sample(chars, _length)) | |
filename = f'{output_dir}{name}_{rand_part}{suffix}' | |
return filename if not os.path.exists(filename) else unique_filename_4sure(_length, _break_recursion - 1) | |
truly_unique_full_path = unique_filename_4sure(length, break_recursion) | |
return truly_unique_full_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment