import os
import shutil
def sort_files_by_extension(source_directory):
# Get all files in the source directory
files = [f for f in [Link](source_directory) if [Link]([Link](source_directory, f))]
# Loop over each file and sort based on its extension
for file in files:
# Get the file extension (e.g., '.txt', '.jpg', '.pdf')
file_extension = [Link](file)[1].lower().strip('.')
# Skip files with no extension
if not file_extension:
file_extension = 'no_extension'
# Create a new directory for the file extension if it doesn't exist
folder_path = [Link](source_directory, file_extension)
if not [Link](folder_path):
[Link](folder_path)
# Construct the full source and destination paths
source_file_path = [Link](source_directory, file)
destination_file_path = [Link](folder_path, file)
# Move the file into the corresponding extension folder
[Link](source_file_path, destination_file_path)
print(f"Moved {file} to {folder_path}")
if _name_ == "_main_":
# Replace with your source directory path
source_directory = r'C:\path\to\your\directory' # Change this to your folder path
sort_files_by_extension(source_directory)