organize the files of all the subdirectories in python

To organize the files of all subdirectories in python, we can make use of the os module and implement directory traversal using recursion. The os module provides a number of useful methods for working with files and directories. We can use the os.listdir() method to get the list of files and directories in a particular directory, and os.path.isfile() method to check if a particular item in the list is a file or not.

Here's an example code that moves all files with the extension .txt from all subdirectories to a new directory named "TextFiles":

main.py
import os
import shutil

def organize_files(src_dir, dest_dir):
    # iterate over all items in the source directory
    for item in os.listdir(src_dir):
        item_path = os.path.join(src_dir, item)

        # if the item is a file, and has a ".txt" extension
        if os.path.isfile(item_path) and item.endswith(".txt"):
            # then move the file to the destination directory
            shutil.move(item_path, dest_dir)

        # if the item is a directory, recursively call the function on the directory
        elif os.path.isdir(item_path):
            organize_files(item_path, dest_dir)

# call the function with the source directory and destination directory
organize_files("parent_directory", "parent_directory/TextFiles")
745 chars
20 lines

This code recursively traverses all subdirectories of the parent_directory, checks if a file is a .txt file, and moves it to the TextFiles directory. The directory structure of parent_directory remains intact, and only the .txt files are moved to the TextFiles directory.

Note that this is just an example, and you can modify the code to suit your specific needs.

gistlibby LogSnag