---
title: "How to rename images with specific patterns in Python?"  
description: "How to rename images with specific patterns in Python?"  
author: "Revati S Misra"  
published: 2023-07-24  
updated: 2023-07-25  
canonical: https://www.mindstick.com/forum/159259/how-to-rename-images-with-specific-patterns-in-python  
category: "python"  
tags: ["file", "image view", "python"]  
reading_time: 2 minutes  

---

# How to rename images with specific patterns in Python?

How to [rename images](https://www.mindstick.com/forum/159258/how-to-rename-images-name-using-data-frame-in-python) with specific patterns in [Python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-using-python)?

## Replies

### Reply by Aryan Kumar

Here is a Python code that you can use to [rename](https://www.mindstick.com/interview/23303/how-to-rename-extention-of-mdf-file) [images](https://www.mindstick.com/interview/1067/what-is-the-php-predefined-variable-that-tells-the-what-type-of-images-that-php-support) with specific patterns:

Python

```plaintext
import os

def rename_images(directory, pattern):
  """Renames images in the specified directory with the specified pattern."""

  # Get the list of files in the directory.
  files = os.listdir(directory)

  # Iterate over the files.
  for file in files:
    # Get the full path to the file.
    file_path = os.path.join(directory, file)

    # Check if the file is an image.
    if os.path.isfile(file_path) and os.path.splitext(file)[1] in [".jpg", ".png"]:
      # Get the new name of the file.
      new_name = pattern.format(file)

      # Rename the file.
      os.rename(file_path, new_name)

if __name__ == "__main__":
  directory = "/path/to/directory"
  pattern = "image_{:03d}.jpg"

  rename_images(directory, pattern)
```

This code first gets the list of files in the directory. Then, it iterates over the files. For each file, it checks if the file is an image. If the file is an image, it gets the new name of the file using the pattern and renames the file.

To use this code, you need to pass the path to the directory that you want to rename the images in as the first argument and the pattern that you want to use to rename the images as the second argument. For example, to rename the images in the directory `/path/to/directory` using the pattern `image_{:03d}.jpg`, you would run the following code:

Python

```plaintext
rename_images("/path/to/directory", "image_{:03d}.jpg")
```

This code will rename all the images in the directory `/path/to/directory` with the pattern `image_{:03d}.jpg`.


---

Original Source: https://www.mindstick.com/forum/159259/how-to-rename-images-with-specific-patterns-in-python

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
