Open In App

Build a Bulk File Rename Tool With Python and PyQt

Last Updated : 30 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this tutorial, we will learn how to create a file renaming tool using Python and PyQt5. PyQt5 is a set of Python bindings for the cross-platform application framework Qt, which is used to create graphical user interfaces (GUIs). We will use the OS module to interact with the file system, and the QFileDialog and QMessageBox classes from PyQt5 to allow the user to select a folder and display messages, respectively.

Our file renaming tool will have a simple user interface with a line edit for displaying the selected folder, a line edit for the search pattern, a line edit for the replacement string, and a rename button. When the rename button is clicked, the tool will search for all the files in the selected folder whose names contain the search pattern and rename them using the replacement string.

Steps to Build Bulk File Rename Tool

Step 1: Imports the necessary modules and create a QApplication object. The QApplication class is required for any PyQt5 application with a GUI.

Python3




import os
from PyQt5 import QtWidgets, QtGui
  
import sys
from PyQt5.QtWidgets import QApplication
  
app = QApplication(sys.argv)


Step 2: This code defines the FileRenamer class. The __init__ method of FileRenamer initializes the widget and calls the ‘initUI’ method to set up the widget’s user interface. The ‘initUI’ method creates several widgets, including ‘QLabels’, ‘QLineEdits’, and ‘QPushButtons’, and arranges them using a ‘QGridLayout’. It also sets the window title and icon of the window using ‘setWindowTitle’ and ‘setWindowIcon’.

Python3




class FileRenamer(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
  
        self.initUI()
  
    def initUI(self):
        # Create a label for the folder selection
        self.folderLabel = QtWidgets.QLabel('Folder:')
        # Create a line edit for displaying the selected folder
        self.folderEdit = QtWidgets.QLineEdit()
        # Create a button for selecting the folder
        self.folderButton = QtWidgets.QPushButton('Browse...')
        # Create a label for the search pattern
        self.searchLabel = QtWidgets.QLabel('Search Pattern:')
        # Create a line edit for the search pattern
        self.searchEdit = QtWidgets.QLineEdit()
        # Create a label for the replacement string
        self.replaceLabel = QtWidgets.QLabel('Replacement:')
        # Create a line edit for the replacement string
        self.replaceEdit = QtWidgets.QLineEdit()
        # Create a rename button
        self.renameButton = QtWidgets.QPushButton('Rename')
  
        # Create a grid layout and add the widgets to it
        layout = QtWidgets.QGridLayout()
        layout.addWidget(self.folderLabel, 0, 0)
        layout.addWidget(self.folderEdit, 0, 1)
        layout.addWidget(self.folderButton, 0, 2)
        layout.addWidget(self.searchLabel, 1, 0)
        layout.addWidget(self.searchEdit, 1, 1)
        layout.addWidget(self.replaceLabel, 2, 0)
        layout.addWidget(self.replaceEdit, 2, 1)
        layout.addWidget(self.renameButton, 3, 1)
        self.setLayout(layout)
  
        # Set the window title
        self.setWindowTitle('Bulk File Rename Tool')
        # Set the window icon
        self.setWindowIcon(QtGui.QIcon('icon.png'))
  
        # Connect the folder selection button to the folderSelection method
        self.folderButton.clicked.connect(self.folderSelection)
        # Connect the rename button to the renameFiles method
        self.renameButton.clicked.connect(self.renameFiles)


Step 3: The ‘folderSelection’ method is connected to the folder selection button’s clicked signal. When the button is clicked, it shows a folder selection dialog and sets the selected folder in the line edit.

Python3




def folderSelection(self):
    # Show a folder selection dialog and set the selected
  # folder in the line edit
    folder = QtWidgets.QFileDialog.
                getExistingDirectory(self, 'Select Folder')
    self.folderEdit.setText(folder)


Step 4: The ‘renameFiles’ method is connected to the rename button’s clicked signal. When the button is clicked, it gets the folder, search pattern, and replacement string from the line edits and renames all the files in the folder whose names contain the search pattern using the replacement string. If the rename operation is successful, it shows a message box to confirm that the files have been renamed.

Python3




def renameFiles(self):
    # Get the folder, search pattern, and replacement 
    # string from the line edits
    folder = self.folderEdit.text()
    search = self.searchEdit.text()
    replace = self.replaceEdit.text()
  
    # Check if the folder and search pattern are not empty
    if folder and search:
        # Loop through all the files in the folder
        for filename in os.listdir(folder):
            # Check if the file matches the search pattern
            if search in filename:
                # Get the file path
                filepath = os.path.join(folder, filename)
                # Separate the file name and file extension
                file_name, file_ext = os.path.splitext(filename)
                # Generate the new file name by replacing the 
                # search pattern with the replacement string
                new_file_name = file_name.replace(search, replace)
                # Generate the new file name with the file extension
                new_name = new_file_name + file_ext
                # Generate the new file path
                new_path = os.path.join(folder, new_name)
                # Rename the file
                os.rename(filepath, new_path)
  
    # Show a message box to confirm that the files have been renamed
    QtWidgets.QMessageBox.information(
        self, 'Renamed', 'Files have been renamed')


Complete Code 

Finally, the script creates an instance of the FileRenamer widget and shows it using show. The app.exec_ method enters the main event loop and waits until the FileRenamer widget is closed. When the widget is closed, the script exits the event loop and terminates.

Python3




import os
from PyQt5 import QtWidgets, QtGui
  
import sys
from PyQt5.QtWidgets import QApplication
  
app = QApplication(sys.argv)
  
  
class FileRenamer(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
  
        self.initUI()
  
    def initUI(self):
        # Create a label for the folder selection
        self.folderLabel = QtWidgets.QLabel('Folder:')
        # Create a line edit for displaying the selected folder
        self.folderEdit = QtWidgets.QLineEdit()
        # Create a button for selecting the folder
        self.folderButton = QtWidgets.QPushButton('Browse...')
        # Create a label for the search pattern
        self.searchLabel = QtWidgets.QLabel('Search Pattern:')
        # Create a line edit for the search pattern
        self.searchEdit = QtWidgets.QLineEdit()
        # Create a label for the replacement string
        self.replaceLabel = QtWidgets.QLabel('Replacement:')
        # Create a line edit for the replacement string
        self.replaceEdit = QtWidgets.QLineEdit()
        # Create a rename button
        self.renameButton = QtWidgets.QPushButton('Rename')
  
        # Create a grid layout and add the widgets to it
        layout = QtWidgets.QGridLayout()
        layout.addWidget(self.folderLabel, 0, 0)
        layout.addWidget(self.folderEdit, 0, 1)
        layout.addWidget(self.folderButton, 0, 2)
        layout.addWidget(self.searchLabel, 1, 0)
        layout.addWidget(self.searchEdit, 1, 1)
        layout.addWidget(self.replaceLabel, 2, 0)
        layout.addWidget(self.replaceEdit, 2, 1)
        layout.addWidget(self.renameButton, 3, 1)
        self.setLayout(layout)
  
        # Set the window title
        self.setWindowTitle('Bulk File Rename Tool')
        # Set the window icon
        self.setWindowIcon(QtGui.QIcon('icon.png'))
  
        # Connect the folder selection button to the folderSelection method
        self.folderButton.clicked.connect(self.folderSelection)
        # Connect the rename button to the renameFiles method
        self.renameButton.clicked.connect(self.renameFiles)
  
    def folderSelection(self):
        # Show a folder selection dialog and set the selected 
        # folder in the line edit
        folder = QtWidgets.QFileDialog.getExistingDirectory(
            self, 'Select Folder')
        self.folderEdit.setText(folder)
  
    def renameFiles(self):
        # Get the folder, search pattern, and replacement 
        # string from the line edits
        folder = self.folderEdit.text()
        search = self.searchEdit.text()
        replace = self.replaceEdit.text()
  
        # Check if the folder and search pattern are not empty
        if folder and search:
            # Loop through all the files in the folder
            for filename in os.listdir(folder):
                # Check if the file matches the search pattern
                if search in filename:
                    # Get the file path
                    filepath = os.path.join(folder, filename)
                    # Separate the file name and file extension
                    file_name, file_ext = os.path.splitext(filename)
                    # Generate the new file name by replacing 
                    # the search pattern with the replacement string
                    new_file_name = file_name.replace(search, replace)
                    # Generate the new file name with the file extension
                    new_name = new_file_name + file_ext
                    # Generate the new file path
                    new_path = os.path.join(folder, new_name)
                    # Rename the file
                    os.rename(filepath, new_path)
  
        # Show a message box to confirm that the files have been renamed
        QtWidgets.QMessageBox.information(
            self, 'Renamed', 'Files have been renamed')
  
  
if __name__ == '__main__':
    # Create an instance of the FileRenamer widget and show it
    renamer = FileRenamer()
    renamer.show()
    sys.exit(app.exec_())


Output:

Let’s have a look at the output result and the steps to be followed to bulk rename files:

The Window of our QT application

Select the folder path where renaming has to be done. This window appears when you click on the browse button in our QT Application

Enter the search and replacement string

The files will be renamed as per the pattern



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads