Published on January 26, 2024By DeveloperBreeze

import os

# Define the directory containing the files to rename
directory_path = 'rename'

try:
    # Check if the directory exists
    if not os.path.exists(directory_path):
        raise FileNotFoundError(f"The directory '{directory_path}' does not exist.")

    # List all files in the directory
    files_list = os.listdir(directory_path)
    if not files_list:
        print(f"The directory '{directory_path}' is empty.")
    else:
        print(f"Renaming files in '{directory_path}'...")

        # Iterate through files and rename them
        for index, file in enumerate(files_list):
            # Get the full path of the current file
            old_file_path = os.path.join(directory_path, file)

            # Skip directories, only process files
            if os.path.isfile(old_file_path):
                # Split the file name and extension
                file_name, file_extension = os.path.splitext(file)

                # Generate a new file name
                # Option 1: Add a new extension
                new_file_name = os.path.join(directory_path, f"{file_name}.newext")

                # Option 2: Rename with an index and new extension
                # new_file_name = os.path.join(directory_path, f"{index}.newext")

                # Rename the file
                os.rename(old_file_path, new_file_name)
                print(f"Renamed: {file} -> {os.path.basename(new_file_name)}")
            else:
                print(f"Skipping directory: {file}")

except FileNotFoundError as e:
    print(e)
except PermissionError:
    print(f"Permission denied: Unable to access or modify files in '{directory_path}'.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Comments

Please log in to leave a comment.

Continue Reading:

File Listing with glob()

Published on January 26, 2024

php

Image Slider

Published on January 26, 2024

javascript

Optimizing Large Database Queries in Laravel

Published on November 16, 2024

php

List Files in a Directory Using os Module

Published on January 26, 2024

python