I need a function that will accept a string to use as a folder name, then append _0 (underscore, zero) to the end of the path name, then check if a folder by that path exists.
If it does NOT exist, it will create a folder using the string followed by a _0 (underscore, zero).
def create_new_dir(folder_name):
i = 0
# Leaf directory
directory = str(folder_name).replace(" ", "_")
# Add trailing '_0'
directory = directory+'_'+str(i)
# Parent Directories
parent_dir = "/Users/Rory"
# Path
path = os.path.join(parent_dir, directory)
isExist = os.path.exists(path)
if not isExist:
# Create a new directory because it does not exist
try:
os.makedirs(path, exist_ok = True)
print("Directory '%s' created successfully" % directory)
except OSError as error:
print("Directory '%s' can not be created" % directory)
But if the path DOES exist already, it will replace _0 with _1. And if a directory by that name ending in _1 already exists, it will swap out _1 for _2, and so on. Better yet, it will just scan the parent directory for folders with the given name followed by an underscore and a number, will then pick the highest of these numbers, and will create a new directory ending in the next highest number. This is the part I'm stuck on.
So if I already have files with the following names:
/Users/Rory/NewDir_0/
/Users/Rory/NewDir_1/
/Users/Rory/NewDir_2/
/Users/Rory/NewDir_3/
/Users/Rory/NewDir_4/
/Users/Rory/NewDir_6/
My function will create a directory named:
/Users/Rory/NewDir_7/