Adventures in Machine Learning

Efficiently Manage Large Files: Build a Bulk File Rename Tool with Python and PyQt

Building a Bulk File Rename Tool with Python and PyQt

Are you tired of manually renaming each file, one by one? Do you have a large number of files that need to be renamed, and you’re struggling to keep up?

Worry not because Python and PyQt have got you covered!

In this article, we’ll discuss how to build a Bulk File Rename Tool using Python and PyQt. The tool will allow you to rename multiple files quickly and efficiently, saving you valuable time and effort.

Project Overview

The Bulk File Rename Tool is a Python script that utilizes PyQt to provide a user-friendly interface. The tool enables the user to select a directory and rename all the files within that directory using customized rules.

The tool also displays a progress bar to keep track of the renaming progress. The pathlib module is utilized for file renaming.

Laying out the Project

Before we dive into building the tool, let’s define the project directory structure and modules of the tool. The tool’s project directory should be structured as follows:

  • bulk_file_rename_tool/
  • ui/
    • main_window.ui
  • bulk_rename.py

The ui/ directory contains the .ui file generated using Qt Designer, and the bulk_rename.py file contains the Python code for the tool.

Outline of the Solution

Now that we have defined the project structure and modules let’s discuss the high-level solution for the problem. The tool will utilize a graphical user interface (GUI) built using PyQt for user interaction.

The user will select the target directory and provide a set of rules to rename the files. The main program will perform the file renaming operation in the background using PyQt threads, displaying the progress on a progress bar.

Step 1: Build the Bulk File Rename Tool’s GUI

The first step in building the Bulk File Rename Tool is creating the GUI using Qt Designer. Qt Designer is a visual editor for designing GUIs for PyQt. The GUI can either be designed using code, or you can use the drag and drop interface of Qt Designer.

Once the GUI is designed in Qt Designer, it generates an XML file that can be converted into Python code.

Converting Qt Designer’s output into Python code

Next, we need to convert the .ui file generated by Qt Designer into Python code.

We can’t execute the .ui file directly in our Python script, so we have to convert it first. The easiest way to do this is by running pyuic5 on the .ui file.

Running pyuic5 will generate a Python file that you can import directly into your Python script. In conclusion, building a Bulk File Rename Tool with Python and PyQt is a straightforward process that can save you a lot of time and effort.

With a user-friendly interface and the power of Python’s pathlib module for file renaming, this tool can help you efficiently manage your files. As we have seen, creating the GUI with Qt Designer and converting it into Python code are the fundamental steps in building the tool.

Stay tuned for the next article, where we’ll discuss how to handle file renames using the Bulk File Rename Tool.

Step 2: Create the PyQt Skeleton Application

After we have converted the .ui file to Python code, the next step is to create the PyQt application’s skeleton.

We need to set up the main window for our Bulk File Rename Tool.

Setting up the Bulk File Rename Tool’s Window

We start by importing the necessary PyQt modules and creating the QApplication and QMainWindow objects.

We then load the UI file from the .py module generated earlier and attach it to the QMainWindow object. Here’s what the code looks like:

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from ui.main_window import Ui_MainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Main UI code
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Save the code to a file named “window.py” and run it using a terminal or command prompt with:

python window.py

This will display the main window of our application. Let’s move on to the next step.

Step 3: Implementing the File Renaming Functionality

Now that we have set up our PyQt application’s skeleton, let’s implement the file renaming functionality. The implementation includes loading files into the application, renaming files using pathlib, using PyQt threads to offload the renaming process, and updating the GUI based on the renaming process progress.

Loading Files into the Application

We need to add a “Select Directory” button, which lets the user choose the directory containing the files they want to rename. When clicked, the button will open a file dialog that allows the user to select a folder.

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Main UI code
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Connect select button to function
        self.ui.select_btn.clicked.connect(self.select_directory)

    def select_directory(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        folder = str(QFileDialog.getExistingDirectory(self, "Select Directory"))

        if folder:
            self.update_file_list(folder)

The select_directory function opens a file dialog that allows the user to select a folder containing the files they want to rename. It then calls the update_file_list function, passing the directory path as an argument.

def update_file_list(self, directory):
    self.ui.file_list.clear()
    self.file_list = []
    for file in os.listdir(directory):
        self.ui.file_list.addItem(file)
        self.file_list.append(file)

The update_file_list function clears the file list and replaces it with the files in the directory passed as an argument.

Renaming Files using pathlib

Now that we have loaded the files into our application, let’s rename them. We’ll be using Python’s pathlib module, which is a convenient way to work with file paths.

def rename_files(self, directory, rules):
    for filename in self.file_list:
        file_path = os.path.join(directory, filename)
        new_filename = rules.apply_rules(filename)
        new_file_path = os.path.join(directory, new_filename)
        pathlib.Path(file_path).rename(new_file_path)

The rename_files function renames the files in the directory passed as an argument, using the file name rules provided. We start by looping through each file in the file list.

We then use os.path.join to create the full path to the file. The rules.apply_rules(filename) function applies the renaming rules to the file name, and the result is saved as new_filename.

Next, we use os.path.join again to create the full path to the new file name. Finally, we call pathlib.Path(file_path).rename(new_file_path) to rename the file.

Using PyQt Threads to Offload the Renaming Process

Renaming files can be a time-consuming process, and we don’t want our GUI to freeze while it’s happening. We’ll use PyQt threads to offload the renaming process to another thread, leaving the GUI thread free to update the progress bar and other parts of the GUI.

from PyQt5.QtCore import *
class RenamingThread(QThread):
    progress = pyqtSignal(int)

    def __init__(self, directory, rules, parent=None):
        super().__init__(parent)
        self.directory = directory
        self.rules = rules

    def run(self):
        for i in range(len(self.file_list)):
            file = self.file_list[i]
            file_path = os.path.join(self.directory, file)
            new_filename = self.rules.apply_rules(file)
            new_file_path = os.path.join(self.directory, new_filename)
            pathlib.Path(file_path).rename(new_file_path)
            self.progress.emit(int((i + 1) * 100 / len(self.file_list)))

We define a RenamingThread class that inherits from QThread. The run function is where we put our file renaming code.

We define a progress signal that we can emit to update the progress bar. From the main thread, we instantiate a RenamingThread object and start it using the start function.

def rename_files(self, directory, rules):
    self.thread = RenamingThread(directory, rules)
    self.thread.progress.connect(self.update_progress_bar)
    self.thread.start()

The rename_files function creates a new RenamingThread object, connects the progress signal to the update_progress_bar function, and starts the thread.

Updating the GUI Based on the Renaming Process Progress

Finally, we’ll update the progress bar based on the progress signal emitted by the RenamingThread.

def update_progress_bar(self, progress):
    self.ui.progressBar.setValue(progress)

The update_progress_bar function updates the progress bar’s value to the percentage complete passed as an argument.

Conclusion

In this article, we discussed how to implement the file renaming functionality of our Bulk File Rename Tool using PyQt and Python’s pathlib module. We learned how to load files into our application and rename them.

We also learned how to use PyQt threads to offload the renaming process and keep the GUI thread free to update the progress bar and other parts of the GUI. By following the steps outlined in this article, you can build a powerful Bulk File Rename Tool that saves you valuable time and effort.

Step 4: Finalizing the Bulk File Rename Tool

In the previous steps, we have built the PyQt application’s skeleton, implemented the file renaming functionality, and integrated PyQt threads to offload the renaming process. Now, the final step is to connect the PyQt widgets to the Python code and run the application.

Connecting the PyQt Widgets to the Python Code

The next step is connecting the PyQt widgets to the Python code we’ve written so far. We use the Qt Designer’s predefined names in the Python code to connect the widgets.

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Main UI code
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Connect select button to function
        self.ui.select_btn.clicked.connect(self.select_directory)

        # Connect rename button to function
        self.ui.rename_btn.clicked.connect(self.rename_files)

        # Configure progress bar
        self.ui.progressBar.setMinimum(0)
        self.ui.progressBar.setMaximum(100)

        # Create file renaming rules object
        self.rules = FileRenamingRules()

    def select_directory(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        folder = str(QFileDialog.getExistingDirectory(self, "Select Directory"))

        if folder:
            self.update_file_list(folder)

    def update_file_list(self, directory):
        self.ui.file_list.clear()
        self.file_list = []
        for file in os.listdir(directory):
            self.ui.file_list.addItem(file)
            self.file_list.append(file)

Here, we’ve connected the select button to the select_directory function, and the rename button to the rename_files function. We’ve also configured the progress bar so that it has the minimum and maximum value of 0 and 100, respectively.

In addition, we’ve created the file renaming rules object and stored it in a local variable.

Running the Application

Finally, we’re ready to run the Bulk File Rename Tool application. We can run it from the command line or terminal window by navigating to the directory containing the application files and running the following command:

python window.py

When the application starts, it will display the main window, where the user can select the directory using the “Select Directory” button.

After selecting the directory, the application displays a list of all the files in that directory on the left-hand side of the GUI. It’s possible to change the renaming rules using the “Naming Rules” tab.

To modify the file naming rules, click the “Naming Rules” tab, and then select the appropriate renaming options from the available dropdown menus. Once the desired file renaming rules are defined, click the “Rename Files” button to start the renaming process.

The application’s progress bar will display the progress of the renaming process until it’s complete. Once completed, the result will be displayed in the directory specified at the beginning of the process.

Running the Bulk File Rename Tool requires some external dependencies, like Python and PyQt5. It’s always wise to ensure that they are installed before executing the application.

Conclusion

In this article, we’ve discussed how to connect the PyQt widgets to the Python code and how to run the Bulk File Rename Tool application. By following the steps provided, you can build a powerful Bulk File Rename Tool that will save you time and effort when working with large files.

Connecting the PyQt widgets to the Python code and running the application are the final steps in creating the Bulk File Rename Tool. When executed successfully, the Bulk File Rename Tool will be a valuable addition to your file management tools, offering a simple and effective way to batch rename your files!

In this article, we’ve explored how to build a Bulk File Rename Tool using Python and PyQt. We discussed how to create a user interface using Qt Designer, converting it into Python code, and building the bulk rename tool’s skeleton application.

We also learned how to implement the file renaming functionality using Python’s pathlib module, how to use PyQt threads to offload the renaming process and keep the GUI responsive, how to connect the PyQt widgets to the Python code, and how to run the application. Building a Bulk File Rename Tool is a valuable addition to your file management system, making batch renaming of files easier and more efficient.

By following the steps outlined in this article, you can build your own Bulk File Rename Tool, streamlining your file management process.

Popular Posts