the-geeky-codes-high-resolution-logo-color-on-transparent-background geeky code red logo
  • Home
  • AI
    AIShow More
    generate vector icons
    Generate Vector Icons with ChatGPT DALLE 3: A Comprehensive Guide
    14 Min Read
    Dalle 3
    Dalle 3: A Step-by-Step Guide to Mastering AI Art Generation
    4 Min Read
    5 Best AI Tools to Convert Images to Video Animations
    5 Best AI Tools to Convert Images to Video Animations
    8 Min Read
    Exploring the Impressive Mistral 7B Model
    Exploring the Impressive Mistral 7B Model for Text Summarization and Coding
    6 Min Read
    The AI Revolution this week
    Must Read – The AI Revolution this week 30 Sep 2023: Integrating AI Tools into Everyday Life
    6 Min Read
  • Tutorial
    • React js
    • Python
    • Javascript
  • AI Tools
Reading: Bulk File Renaming and Special Character Removal – Python
Share
the geeky codesthe geeky codes
Aa
  • AI
  • AI Tools
  • Javascript
  • Python
  • React js
  • Advertise
Search
  • Categories
    • AI
    • AI Tools
    • Javascript
    • Python
    • React js
  • More
    • Advertise
Follow US
Copyright ©2023 The Geeky codes. All Rights Reserved.
the geeky codes > Blog > Tutorial > Python > Bulk File Renaming and Special Character Removal – Python
TutorialPython

Bulk File Renaming and Special Character Removal – Python

thegeekycodes By thegeekycodes 18 July 2024 9 Min Read
Bulk File Renaming and Special Character Removal
SHARE

File Renaming and Special Character Removal | Pyhton

Managing files can be a tedious task, especially when you have a large collection of documents, images, or other digital assets. Renaming multiple files to follow a specific naming convention or cleaning up filenames by removing special characters can be time-consuming if done manually. Fortunately, Python provides a powerful way to automate these tasks, making your file management more efficient and organized.

Contents
File Renaming and Special Character Removal | PyhtonBulk File RenamingRemoving Special Characters from FilenamesRemove Digits from FilenamesChange File ExtensionsDate-based RenamingConclusion

we’ll explore Five Python scripts that simplify file management: one for bulk file renaming and another for removing special characters from filenames. These scripts can save you valuable time and help maintain a clean and consistent file structure.

Bulk File Renaming

Problem: You have a directory filled with files, and you want to rename them systematically. For instance, you might want to add a prefix or suffix to each filename or increment a number for each file.

Solution: Python’s os and re modules come to the rescue with a script that allows you to rename multiple files based on a pattern and a replacement string. Here’s the code:

import os
import re

# Set the directory path and pattern replacement here
directory = r"D://testing"  # Example directory path
pattern = r" "  # Match a single space character
replacement = "_"  # Replace with an underscore


def bulk_rename(directory, pattern, replacement):
    try:
        # Ensure the directory exists
        if not os.path.exists(directory):
            raise FileNotFoundError(f"Directory '{directory}' not found.")

        # Iterate through files and directories in the directory
        for entry in os.scandir(directory):
            old_name = entry.name
            new_name = re.sub(pattern, replacement, old_name)

            # Check if the names are different
            if old_name != new_name:
                old_path = os.path.join(directory, old_name)
                new_path = os.path.join(directory, new_name)

                # Rename the file or directory
                os.rename(old_path, new_path)
                print(f"Renamed: {old_path} -> {new_path}")

        print("Bulk rename complete.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")


if __name__ == "__main__":
    bulk_rename(directory, pattern, replacement)

In this script, you set the directory path, specify a pattern to match (such as spaces), and provide a replacement string (such as an underscore). The script then iterates through the files in the specified directory, matches the pattern in the filenames, and renames them accordingly.

Removing Special Characters from Filenames

Problem: Filenames with special characters can cause issues in various applications, such as web hosting or cross-platform compatibility. You want to clean up your filenames by removing all special characters.

Solution: Python offers another script that addresses this problem. It removes special characters (anything that is not a letter, digit, period, or underscore) from filenames within a directory. Here’s the code:

import os
import re

# Set the directory path here
directory = r"D://testing"  # Example directory path

def bulk_remove_special_characters(directory):
    try:
        # Ensure the directory exists
        if not os.path.exists(directory):
            raise FileNotFoundError(f"Directory '{directory}' not found.")

        # Define a pattern to match special characters
        pattern = r'[^a-zA-Z0-9\._]'

        # Iterate through files in the directory
        for entry in os.scandir(directory):
            if entry.is_file():
                old_filename = entry.name

                # Use re.sub to remove special characters
                new_filename = re.sub(pattern, '', old_filename)

                # Check if the filenames are different
                if old_filename != new_filename:
                    old_path = os.path.join(directory, old_filename)
                    new_path = os.path.join(directory, new_filename)

                    # Rename the file
                    os.rename(old_path, new_path)
                    print(f"Renamed: {old_path} -> {new_path}")

        print("Bulk removal of special characters complete.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    bulk_remove_special_characters(directory)

💁 Check out our other articles😃

 👉  Generate a free Developer Portfolio website with AI prompts

 👉  Email Validation in Python

Remove Digits from Filenames

Problem: You have a directory filled with files containing digits in their filenames, and you want to remove all the digits, effectively leaving only letters and other characters.

Solution: Python comes to the rescue again with a script that removes digits from filenames within a directory. Here’s the code:

import os
import re

# Set the directory path here
directory = r"D://testing"  # Example directory path

def remove_digits_from_filenames(directory):
    try:
        # Ensure the directory exists
        if not os.path.exists(directory):
            raise FileNotFoundError(f"Directory '{directory}' not found.")

        # Define a pattern to match digits
        pattern = r'\d'

        # Iterate through files in the directory
        for entry in os.scandir(directory):
            if entry.is_file():
                old_filename = entry.name

                # Use re.sub to remove digits
                new_filename = re.sub(pattern, '', old_filename)

                # Check if the filenames are different
                if old_filename != new_filename:
                    old_path = os.path.join(directory, old_filename)
                    new_path = os.path.join(directory, new_filename)

                    # Rename the file
                    os.rename(old_path, new_path)
                    print(f"Renamed: {old_path} -> {new_path}")

        print("Bulk removal of digits from filenames complete.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    remove_digits_from_filenames(directory)

Change File Extensions

Problem: You have a directory with files in one file format (e.g., JPG), and you want to change the extensions of all those files to another format (e.g., PNG).

Solution: Python provides a script that allows you to change the file extensions of all files within a directory. Here’s the code:

import os

# Set the directory path here
directory = r"D://testing"  # Example directory path
old_extension = '.jpg'  # Specify the old file extension
new_extension = '.png'  # Specify the new file extension

def change_file_extensions(directory, old_extension, new_extension):
    try:
        # Ensure the directory exists
        if not os.path.exists(directory):
            raise FileNotFoundError(f"Directory '{directory}' not found.")

        # Iterate through files in the directory
        for entry in os.scandir(directory):
            if entry.is_file() and entry.name.lower().endswith(old_extension.lower()):
                old_path = os.path.join(directory, entry.name)
                new_path = os.path.join(directory, entry.name[:-len(old_extension)] + new_extension)

                # Rename the file by changing the extension
                os.rename(old_path, new_path)
                print(f"Renamed: {old_path} -> {new_path}")

        print(f"Bulk change of file extensions to {new_extension} complete.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    change_file_extensions(directory, old_extension, new_extension)

Date-based Renaming

Problem: You have a directory filled with files named in “YYYY-MM-DD” format, and you want to rearrange the filenames to “DD-MM-YYYY” format.

Solution: Python offers a script that allows you to perform date-based renaming of files within a directory. Here’s the code:

import os
import re

# Set the directory path here
directory = r"D://testing"  # Example directory path

def date_based_renaming(directory):
    try:
        # Ensure the directory exists
        if not os.path.exists(directory):
            raise FileNotFoundError(f"Directory '{directory}' not found.")

        # Define a pattern to match dates in "YYYY-MM-DD" format
        pattern = r'(\d{4})-(\d{2})-(\d{2})'

        # Iterate through files in the directory
        for entry in os.scandir(directory):
            if entry.is_file():
                old_filename = entry.name

                # Use re.sub to rearrange the date in "DD-MM-YYYY" format
                new_filename = re.sub(pattern, r'\3-\2-\1', old_filename)

                # Check if the filenames are different
                if old_filename != new_filename:
                    old_path = os.path.join(directory, old_filename)
                    new_path = os.path.join(directory, new_filename)

                    # Rename the file
                    os.rename(old_path, new_path)
                    print(f"Renamed: {old_path} -> {new_path}")

        print("Date-based renaming complete.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    date_based_renaming(directory)

Conclusion

These Python scripts provide efficient solutions for bulk file renaming and removing special characters from filenames. Whether you need to clean up a cluttered directory, standardize file names, or prepare files for a specific application, automation with Python can make these tasks significantly easier and faster. By adapting and using these scripts, you can take control of your file management processes and ensure a more organized and consistent file structure.

TAGGED: file renaming, Python

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Copy Link Print
Previous Article Logging and Notifying Errors in Python Logging and Notifying Errors in Python: A Multi-Channel Approach
Next Article Image Processing with OpenCV in Python Image Processing with OpenCV in Python
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Twitter Follow
Telegram Follow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!

Most Popular
Advanced Routing Techniques in Nextjs 15
Advanced Routing Techniques in Next js 15
20 November 2024
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK
20 November 2024
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript
20 November 2024
Google Analytics 4 in Nextjs 14
How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]
20 November 2024
docker compose
Getting Started with Docker Compose
20 November 2024

You Might Also Like

Advanced Routing Techniques in Nextjs 15
TutorialNextjs

Advanced Routing Techniques in Next js 15

7 Min Read
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
TutorialNextjs

Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK

4 Min Read
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
TutorialNextjs

How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript

9 Min Read
Google Analytics 4 in Nextjs 14
TutorialNextjs

How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]

6 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!

the geeky codes geeky code red logo

Providing valuable resources for developers in the form of code snippets, software tutorials, and AI related content.

About

  • About Us
  • Contact
  • Terms and Conditions
  • Privacy Policy
  • Disclaimer
  • Affiliate Disclosure

Resource

  • The Art of AI Prompt Engineering: Crafting Effective Inputs for AI Models

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
© 2023 The Geeky Codes. All Rights Reserved
We are happy to see you join Us!

🔥📢Subscribe to our newsletter and never miss our latest code snippets, tutorials and AI updates

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?