Create a File Organizer Using Python 📂

Create a File Organizer Using Python 📂

By Pratyush Mishra

·

2 min read

Table of contents

No heading

No headings in the article.

Hi everyone👋,In this article we will be creating a simple Python script that organizes files based on their extensions into separate folders:

import os

import shutil

# Function to organize files

def organize_files(folder_path):

# Get all files in the folder

files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]

# Create folders for each file extension

for file in files:

file_extension = os.path.splitext(file)[1][1:]

folder_name = file_extension.upper() + "_Files"

# Create folder if it doesn't exist

if not os.path.exists(os.path.join(folder_path, folder_name)):

os.makedirs(os.path.join(folder_path, folder_name))

# Move the file to the respective folder

shutil.move(os.path.join(folder_path, file), os.path.join(folder_path, folder_name, file))

print("File organization complete.")

# Provide the folder path to organize

folder_path = "C:/Path/To/Folder"

# Call the organize_files function

organize_files(folder_path)

This script utilizes the os module to work with file paths and the shutil module to move files. It defines the organize_files function that takes the folder_path as input. It gets all the files in the specified folder using os.listdir and filters out directories using os.path.isfile.

Next, it iterates over each file and extracts the file extension using os.path.splitext. It then creates a folder with the extension name (e.g., "TXT_Files" for ".txt" files) by converting the extension to uppercase and appending "_Files". If the folder doesn't exist, it creates one using os.makedirs.

Finally, it moves the file into the respective folder using shutil.move, specifying the source file path and the destination folder path.

To use this script, you need to provide the folder_path variable with the path to the folder you want to organize. Make sure to replace "C:/Path/To/Folder" with the actual path to your folder.

When you run the script, it will organize the files in the specified folder based on their extensions, creating separate folders for each file type and moving the files into their corresponding folders.

Alright, guys! I hope this article was helpful for you, and if was then leave your comments below. I will meet you in another article until then KEEP CODING🤗.

Â