0% found this document useful (0 votes)
2 views2 pages

program 1

The document contains a Python script that sorts files in a specified directory by their file extensions. It creates subdirectories for each file extension and moves the corresponding files into these folders. The script handles files without extensions by placing them in a 'no_extension' folder.
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)
2 views2 pages

program 1

The document contains a Python script that sorts files in a specified directory by their file extensions. It creates subdirectories for each file extension and moves the corresponding files into these folders. The script handles files without extensions by placing them in a 'no_extension' folder.
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
You are on page 1/ 2

import os

import shutil

def sort_files_by_extension(source_directory):

# Get all files in the source directory

files = [f for f in os.listdir(source_directory) if os.path.isfile(os.path.join(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 = os.path.splitext(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 = os.path.join(source_directory, file_extension)

if not os.path.exists(folder_path):

os.makedirs(folder_path)

# Construct the full source and destination paths

source_file_path = os.path.join(source_directory, file)

destination_file_path = os.path.join(folder_path, file)

# Move the file into the corresponding extension folder

shutil.move(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)

You might also like