How to merge folders in every subdirectory using python code?

How to merge folders in every subdirectory using python code?

Problem Description:

my directory now.[1]
I want to combine every Sub in every Folder so it should look something like this [2]
[1]: https://i.stack.imgur.com/xz7FJ.png
[2]: https://i.stack.imgur.com/scK48.png

Solution – 1

You can iterate through all the files/dirs in a directory using os.walk().

We are just iterating over all files in a dir and then moving them to a destination directory using os.rename()

import os
directory = '/tmp/dataset'

def move_all_files_to_destination_dir(original_dir, destination_dir):
    # moves all NESTED files in original_dir to destination_dir
    files = []
    for root, dirs, files in os.walk(original_dir):
        for name in files:
            os.rename(root + os.sep + name, destination_dir + os.sep + name)
    
subdirs = [f.path for f in os.scandir(directory) if f.is_dir()]   # [Folder1, Folder2]
for d in subdirs:
    move_all_files_to_destination_dir(d, d)
    # remove the subdirectories of d after we have moved all files under it
    for sub in os.scandir(d):
        if sub.is_dir():
            shutil.rmtree(sub)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject