How to merge multiple folders into one folder using Python ?
- Get the current directory and the list of the folders you want to merge.
- Loop through the list of folders and store their content in a list. Here, we have stored them in the dictionary so that we can have the name of the folder as a key and its content as a value list.
- Specify the folder in which you want to merge all the other folders. If the folder exists then we are good to go but if the folder does not exist then create a new folder.
- Loop through the dictionary and move all the content of all the listed folders inside the merge folder.
Let’s implement this approach step by step:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Step 1: Below code does the following:
- Get the current directory.
- List all the folders that you want to merge.
- Stores content of all the listed folders in the dictionary with folder name as key and its content as a value list.
Step 2: Creates the merge folder if it does not already exist.
Step 3: Below code does the following:
- Loop through the dictionary with all the folders.
- Now loop through the content of each folder and one by one move them to the merge folder.
Folder structure before running the above program.
Folder 1 File 1 File 2 Folder 2 File 3 File 4 Folder 3 File 5 File 6 Folder 4 File 7 File 8 merge_folder (Empty) move_script.py
Folder structure after running the above program.
Folder 1 (Empty) Folder 2 (Empty) Folder 3 (Empty) Folder 4 (Untouched) File 7 File 8 merge_folder File 1 File 2 File 3 File 4 File 5 File 6 move_script.py
Program in Working :