Extract name of main subfolder, create new subfolder, and move files from source to destination

30 Views Asked by At

I'm fairly new to python but I'm trying to write a code that essentially looks at all the folders in my source path, extract the names of the folders in the source and create new folders with a similar name as those folders, and move the corresponding image files within those folders in the source path to the destination path. Below is my code:

import os
import shutil

srcpath = "SOURCE"
destpath = "DESTINATION"

for root, subFolders, files in os.walk(srcpath):
    # Create new folders in destination path for storing images
    for subFolder in subFolders:
        # Extract folder names in source path
        new_subFolder = os.path.join(destpath, subFolder[0:-14])
        # Create new folders
        if not os.path.isdir(new_subFolder):
            os.makedirs(new_subFolder)
            print(f'Created: {new_subFolder}')

# Having trouble here
dir_list = os.listdir(destpath)

for root, subFolders, files in os.walk(srcpath):
    for i in range(len(dir_list)):
        for file in files:
            print(file)
            new_file = os.path.join(dir_list[i], file)
            print(f'New file path: {new_file}')
            # shutil.move(os.path.join(root, file), new_file)

The second part is where I'm stuck. I've gotten the code to extract the relevant information for creating new subfolders but can't get it to create the appropriate destination path string to move those files. What it currently does is move everything to the last folder, which is not what I want it to do. The files in the original source folders needs to be moved into the corresponding destination folders. Also not quite sure how to make the code more elegant by only running the loop once.

Appreciate any input. TIA!

0

There are 0 best solutions below