Python - Move all files from subfolders to main folder

Python - Move all files from subfolders to main folder

To move all files from subfolders to the main folder, you can use Python's built-in libraries: os and shutil. Here's a step-by-step breakdown and the code to achieve this:

  1. Use os.walk() to navigate through the directory structure.
  2. For each file found, use shutil.move() to move it to the main directory.

Here's a simple script to move all files from subfolders to the main folder:

import os import shutil def move_files_to_main_folder(main_folder): # Walk through all subfolders for foldername, subfolders, filenames in os.walk(main_folder): for filename in filenames: # Construct the full (absolute) path to the file file_path = os.path.join(foldername, filename) # Move the file to the main folder shutil.move(file_path, main_folder) main_directory = '/path/to/your/main/folder' move_files_to_main_folder(main_directory) 

Replace '/path/to/your/main/folder' with the path to your main directory, and the script will move all files from its subdirectories to this main directory. Make sure to backup your data or test on a small dataset first to ensure it works as expected for your specific scenario.


More Tags

angular-google-maps x11 sharpssh bootstrap-datepicker status asp.net-web-api iconbutton single-sign-on azure-application-gateway caliburn.micro

More Programming Guides

Other Guides

More Programming Examples