This Python script organizes files in a directory by moving them into subfolders based on their file extensions. It’s useful for decluttering download folders, project directories, or any location where files tend to accumulate without organization.
import os
import shutil
def organize_files(directory: str):
"""Organize files in the specified directory by their extensions."""
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
# Skip directories
if os.path.isdir(filepath):
continue
# Get file extension and create subfolder name
_, ext = os.path.splitext(filename)
ext = ext[1:].lower() # Remove dot and normalize case
if not ext: # Handle files without extension
ext = "no_extension"
# Create subdirectory if it doesn't exist
subdir = os.path.join(directory, ext)
os.makedirs(subdir, exist_ok=True)
# Move file to subdirectory
new_path = os.path.join(subdir, filename)
shutil.move(filepath, new_path)
print(f"Moved: {filename} -> {ext}/")
if __name__ == "__main__":
target_dir = input("Enter directory path to organize: ").strip()
if os.path.isdir(target_dir):
organize_files(target_dir)
print("Organization complete!")
else:
print("Error: Invalid directory path")
.txt, .jpg) and creates a corresponding subfolder if it doesn’t exist.no_extension folder.directory_cleaner.py.python directory_cleaner.py.Note: Always back up important files before running automation scripts that move files.