DeveloperBreeze

Snippets Programming Tutorials, Guides & Best Practices

Explore 196+ expertly crafted snippets tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Image Slider

Code January 26, 2024
javascript

No preview available for this content.

Batch File Renaming Using os Module

Code January 26, 2024
python

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}")