Batch File Search and Renaming with Python

If it is necessary to rename a batch of files, where both the existing and new file names exist in an Excel spreadsheet, Python can be used to automate the renaming process.

In the example below, a spreadsheet called “Documents to rename.xlsx” contains the file name information. Column ‘A’ contains the existing file name, without the file extension, column ‘B’ contains the new file name, if available, without the extension, and column ‘C’ is for notes to be added during the renaming process.

Existing File Name New File Name Notes
OldFileName1 NewFileName1
OldFileName2
OldFileName3 NewFileName3
OldFileName4 NewFileName4

First of all, the path to the above document, as well as to the files to be renamed, is set and a check is made to see if they exist. If they do exist, the document containing the file names is opened and the file name information on the first sheet is processed. The current and new file names are extracted from column ‘A’ and the next column to the right, column ‘B’. A check is made to see if the file exists with the current name and if it does the file gets renamed to the new name, providing there is one available. Feedback is added as to whether the file was renamed or not, or, if it had already been renamed, in the second column to the right of the original file name. Overall feedback is also given as to the total number of files renamed. Finally, ‘try-except’ blocks are used to handle errors with opening, saving and closing files.

# Import required modules.
import openpyxl
import os
import re
import shutil

# File names workbook.
pathNamesDoc = "C:\\Demo\\Rename\\Documents to rename.xlsx"
xlNamesWorkbook = None
xlNamesWorksheet = None

# Path to documents to rename.
pathDocsRename = "C:\\Demo\\"

# Check if the file and folder paths exist.
if os.path.isfile(pathNamesDoc) and os.path.exists(pathDocsRename):

    try:

        # Open the file names workbook and assign to a variable.
        xlNamesWorkbook = openpyxl.load_workbook(pathNamesDoc)

    except PermissionError as e:

        # Message stating that workbook can't be opened.
        print("Unable to open file names workbook.")

        # Stop program execution.
        quit()

    # Select the first sheet.
    xlNamesWorksheet = xlNamesWorkbook.worksheets[0]

    # Column.
    xlNamesWorksheetCol = "A"

    # File extension for documents to rename.
    fileExtension = ".docx"

    # Renamed file count.
    filesRenamed = 0

    # Check if there are any files to rename.
    if xlNamesWorksheet.max_row <= 1:

        # Message stating no files to rename.
        print("There are no files to rename.")

    else:

        # Process rows from the second to the last.
        for row in range(2, xlNamesWorksheet.max_row + 1):

            # Make sure there is a value in selected cell.
            if not xlNamesWorksheet[xlNamesWorksheetCol + str(row)].value is None:

                # Extract the current and new file name.
                # New file name one column to the right of current file name.
                currentFileName = xlNamesWorksheet[xlNamesWorksheetCol
                                                   + str(row)].value
                newFileName = xlNamesWorksheet[(chr(ord(xlNamesWorksheetCol) + 1))
                                               + str(row)].value

                # Check if the file exists and a new name has been provided.
                if os.path.isfile(pathDocsRename + currentFileName
                                  + fileExtension) and not newFileName is None:

                    # Check if the new file name is valid.
                    fileNameCheck = re.compile('[^\w,\s-]')
                    if not fileNameCheck.search(newFileName):

                        try:

                            # Rename the file.
                            shutil.move(pathDocsRename + currentFileName + fileExtension,
                                        pathDocsRename + newFileName + fileExtension)

                            # Add message stating file has been renamed.
                            # Two columns to the right of the original file name.
                            xlNamesWorksheet[(chr(ord(xlNamesWorksheetCol) + 2))
                                             + str(row)].value = "File has been renamed."

                            # Increment the files renamed count.
                            filesRenamed += 1

                        except PermissionError as e:

                            # Add message stating file can't be renamed.
                            # Two columns to the right of the original file name.
                            xlNamesWorksheet[(chr(ord(xlNamesWorksheetCol) + 2))
                                             + str(row)].value = "File could not be renamed."

                    else:

                        # Add message stating no new valid name provided.
                        xlNamesWorksheet[(chr(ord(xlNamesWorksheetCol) + 2))
                                         + str(row)].value = \
                            "No new valid file name provided."

                else:

                    # Check if new file name has been provided.
                    if newFileName is None:

                        # Add message stating no new file name provided.
                        # Two columns to the right of the original file name.
                        xlNamesWorksheet[(chr(ord(xlNamesWorksheetCol) + 2))
                                         + str(row)].value = \
                            "No new valid file name provided."

                    # Check if file has already been renamed.
                    elif os.path.isfile(pathDocsRename + newFileName
                                        + fileExtension):

                        # Add message stating file already renamed.
                        xlNamesWorksheet[(chr(ord(xlNamesWorksheetCol) + 2))
                                         + str(row)].value = \
                            "File has already been renamed."

                    else:

                        # Add message stating file does not exist.
                        xlNamesWorksheet[(chr(ord(xlNamesWorksheetCol) + 2))
                                         + str(row)].value = \
                            "File does not exist."

        try:

            # Save the file names workbook.
            xlNamesWorkbook.save(pathNamesDoc)

        except PermissionError as e:

            # Message stating file names workbook could not be saved.
            print("The file names workbook could not be saved.")

        # Feedback on renamed files.
        if filesRenamed == 0:

            print("No files were renamed.")

        elif filesRenamed == 1:

            print(str(filesRenamed) + " file renamed successfully.")

        else:

            print(str(filesRenamed) + " files renamed successfully.")

    # Close names workbook.
    xlNamesWorkbook.close()

else:

    # Check if its the file or folder path that doesn't exist.
    if not os.path.isfile(pathNamesDoc):

        # Error message if file names workbook doesn't exist.
        print("The document containing the file names does not exist.")

    else:

        # Error if folder path for documents to be renamed doesn't exist.
        print("The location of the files to rename does not exist.")