'Python - create sequentially numbered directories

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/


Solution 1:[1]

If you want to make it incremental from existing folders. The program would need to be able to "know" what is the last folder.
So to do that we can find the existing folders, and then perform string manipulation to get the latest number

# To an array of all folders in the directory
arr = os.listdir("/Users/Rory")

folder_nums = []

for folder_name in arr:
  
  # Spilts the string into ["NewDir","1"]
  folder_nums.append( int(folder_name.split("_")[1]) )

new_folder_num = max(folder_nums) + 1 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bchooxg