pythonfiledirectorycopyfile-rename

Duplicating Folder and files multiple times and rename folders and files sequentially


I have a templated folder structure with predefined files in folders and also blank folders. I'm looking to duplicate this folder structure multiple times while updating the folders and files sequentially. Ideally having an option to the number of copies to make.

I have a system for creating the folders and file names via tokens, but no way of duplicating those folders and files sequentially. Could any one help?

A simple overview of this would be:

Existing Folders:

RootFolder
 shot_010
     folder
         shot_010_comp_v01.comp

What I would like to create via duplicating folders and files:

RootFolder
 shot_010
     folder
         shot_010_comp_v01.comp

RootFolder
 shot_020
     folder
         shot_020_comp_v01.comp

RootFolder
 shot_030
     folder
         shot_030_comp_v01.comp

Solution

  • To generate new directory names, you could do something like this:

    def get_dir_name(count: int):
        for i in range(count):
            yield f"shot_{i:02}0"
    
    dir_names = get_dir_name(100)
    

    and then call next(dir_names) whenever you need a new one. Same pattern applies to the file names.

    When it comes to copying, you could use shutil.copytree, to which you specify source directory and destination dir and then shutil.move to rename it accordingly. Or you could write a function that copies everything step by step, renaming each directory and file along the way. The complete solution could look like this:

    import os
    import shutil
    
    
    def get_dir_name(count: int):
        for i in range(1, count + 1):
            yield f"shot_{i:02}0"
    
    def get_file_name(count: int):
        for i in range(1, count + 1):
            yield f"shot_{i:02}0_comp_v01.comp"
    
    
    def duplicate_shot_folder(count: int):
        for file_, dir_ in zip(get_file_name(count), get_dir_name(count)):
            os.makedirs(f"{dir_}/folder", exist_ok=True)
            shutil.copyfile("shot_010/folder/shot_010_comp_v01.comp", f"{dir_}/folder/{file_}")
    

    Bear in mind that you cannot have multiple "RootFolder" directories, hence I've omitted it.