Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Automation Script to Rename All Files in Directory With a Custom Pattern Name in OS Module

Posted on February 12, 2023

 

 

Welcome folks today in this blog post we will be writing the python script to automatically rename all the files present inside the directory with a custom pattern name using the os module. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an app.py file and copy paste the following code

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import os
 
# specify the directory path
directory_path = "images"
 
# specify the custom pattern for file names
file_name_pattern = "file_"
 
# get a list of all files in the directory
files = os.listdir(directory_path)
 
# loop through each file
for index, file in enumerate(files):
    # get the absolute path of the file
    file_path = os.path.join(directory_path, file)
    # check if the file is a file (not a directory)
    if os.path.isfile(file_path):
        # get the file extension
        file_extension = os.path.splitext(file)[1]
        # construct the new file name using the custom pattern and file extension
        new_file_name = file_name_pattern + str(index) + file_extension
        # construct the absolute path of the new file name
        new_file_path = os.path.join(directory_path, new_file_name)
        # rename the file
        os.rename(file_path, new_file_path)

 

 

As you can see in the above code you need to replace the path of the directory where all the files are present and then it will loop through all the files with different extensions as well and it will rename the files with the provided pattern in the above code. You can edit the pattern according to your choice. Now you need to create the images folder and store the files as shown below

 

 

 

Recent Posts

  • Node.js Tutorial to Export Images to PDF Document With Effects Using FilePix Library in Javascript
  • Node.js Tutorial to Export All Pages of PDF Document to Images and Save it in Javascript
  • Node.js OfficeGen Example to Add Text & Images in Powerpoint Presentation in Javascript
  • Node.js OfficeGen Example to Generate Excel Files By Adding Data inside Cells & Sheets in Javascript
  • Node.js OfficeGen Example to Create Word Docx Files & Add Text Images inside it Using Javascript
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme