0% found this document useful (0 votes)
30 views1 page

Sort Files by Extension in Python

The document contains a Python script that sorts files in a specified directory based on their file extensions. It creates subfolders for each file extension and moves the corresponding files into these folders. The script skips directories and files without extensions while providing feedback on the moved files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views1 page

Sort Files by Extension in Python

The document contains a Python script that sorts files in a specified directory based on their file extensions. It creates subfolders for each file extension and moves the corresponding files into these folders. The script skips directories and files without extensions while providing feedback on the moved files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import os

import shutil

def sort_files(directory):

# Go through each file in the directory

for filename in [Link](directory):

# Create the full file path

filepath = [Link](directory, filename)

# Only sort files (skip directories)

if [Link](filepath):

# Get the file extension (e.g., 'txt' from '[Link]')

ext = [Link](filename)[1][1:].lower() # Remove the dot and lowercase

# Skip files with no extension

if ext:

# Create the folder name for the extension

target_folder = [Link](directory, ext)

# Make the folder if it doesn't exist

if not [Link](target_folder):

[Link](target_folder)

# Move the file into the extension folder

[Link](filepath, [Link](target_folder, filename))

print(f"Moved {filename} to folder: {ext}")

# Replace 'your_directory_path' with the directory you want to sort

sort_files('your_directory_path')

You might also like