DeveloperBreeze

Batch File Renaming Using os Module

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

Related Posts

More content you might like

Tutorial
php

Optimizing Large Database Queries in Laravel

Debugbar highlights duplicate queries and slow-performing SQL.

Use Laravel Telescope to monitor database queries in production environments:

Nov 16, 2024
Read More
Tutorial
bash

Finding the Top 10 Biggest Files on an Ubuntu Server

Replace /path/to/directory with the path to the directory you want to search.

Use the following command to find the top 10 largest files:

Aug 11, 2024
Read More
Tutorial
sql

Optimizing SQL Queries: Indexing and Query Optimization Techniques

Avoid SELECT *:

SELECT name, department FROM employees;

Aug 03, 2024
Read More
Code
javascript

Image Slider

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!