Search code examples
pythondirectoryspydercopy-pastesubdirectory

How to copy files from one folder to another taking into account that the file name contains the name of the destination folders in python


I need to copy files from a source folder like this:

enter image description here

And paste them into another folders like these:

enter image description here

As you can see, the destination folder has subfolders with the 1.1 and 1.2 numerations. (The real folder has too many, for that reason is not possible to do a manual "if" comparison)

What I need is the python script walk in the Source folder and evaluate each file to determinate in which destiny folder and subfolder it have to put in.

For example the files "ABC_1.1_files.zip" and "ABC_1.1_test.xlsx" have to paste into folder "ABC" and in subfolder "1.1" and the same with the another files.

I really appreciate your help!


Solution

  • import os
    import shutil
    
    src = "PATH/TO/SOURCE/FOLDER"
    dst = "PATH/TO/DESTINATION/FOLDER"
    
    for file_name in os.listdir(src):
        sub, num = file_name.split("_")[:2]
        new_dst = dst + f"{sub}/{num}/"
        os.makedirs(os.path.dirname(new_dst), exist_ok=True)
        shutil.copy(src, new_dst)