Python - Add Find and Replace statement

405 Views Asked by At

Huge thanks to @d_kennetz for getting my code to its current state, but I keep hitting a wall.

Code reads an excel file into a list and then loops through a folder and renames the files, but it does this in the order of the list and then starting with the first file and working to the last, so if I manually sort the excel list and the files themselves I can accurately rename them BUT I would like to add a find() to the loops so that I can make this program more flexible.

Goal - Add find() so it will loop through a list of current file names (in excel) and then find the correct file in the selected folder and then rename it to the correct new name.

Current Working Code (without Find()):

# File with file name data
file_names = openpyxl.load_workbook(filedialog.askopenfilename())  # Add the file name
file_names_sheet = file_names['piclist2']  # Add the sheet name

# Select the source folder with files in it
folderSource = filedialog.askdirectory()

# New Folder Name
folderDestination = 'Photos Renamed'

# Takes: start cell, end cell, and sheet you want to copy from.
def copyRange(startCol, startRow, endCol, endRow, sheet):
    rangeSelected = []
    # Loops through selected Rows
    for i in range(startRow, endRow + 1, 1):
        # Appends the row to a RowSelected list
        rowSelected = []
        for j in range(startCol, endCol + 1, 1):
            rowSelected.append(sheet.cell(row=i, column=j).value)
        # Adds the RowSelected List and nests inside the rangeSelected
        rangeSelected.append(rowSelected)

    return rangeSelected


def renameFiles():
    print('Processing...')

    # Make a folder for the files
    current_directory = os.getcwd()
    folder_n_path = os.path.join(current_directory, folderDestination)
    print("Files saved to: " + folder_n_path)
    try:
        newFolder = os.makedirs(folder_n_path)

    except:
        print("Folder already exists")
        return

    # Get the Data to make the file names
    selectedRange = copyRange(1, 1, 2, 2, file_names_sheet)
    print(selectedRange)
    # Loop through each row
    for i, filename in zip(selectedRange, os.listdir(folderSource)):
        file_name = str(i[0]) + " " + i[1] + ".jpg"
        filename = os.path.join(folderSource, filename)
        file_name = os.path.join(folderDestination, file_name)
        shutil.copy(filename, file_name)
    print("Done")


go = renameFiles()

Code I attempted adding an if() to but it just says: "File Not Found"

# File with file name data
file_names = openpyxl.load_workbook(filedialog.askopenfilename())  # Add the file name
file_names_sheet = file_names['piclist2']  # Add the sheet name

# Select the source folder with files in it
folderSource = filedialog.askdirectory()

# New Folder Name
folderDestination = 'Photos Renamed'

Added this to loop through the Original Filename Column and add to a list:

def originalFilenameRange(startCol, startRow, endCol, endRow, sheet):
    originalFilenameRange = []
    # Loops through selected Rows
    for i in range(startRow, endRow + 1, 1):
        # Appends the row to a RowSelected list
        rowSelected = []
        for j in range(startCol, endCol + 1, 1):
            rowSelected.append(sheet.cell(row=i, column=j).value)
        # Adds the RowSelected List and nests inside the rangeSelected
        originalFilenameRange.append(rowSelected)

    return originalFilenameRange

# Takes: start cell, end cell, and sheet you want to copy from.
def copyRange(startCol, startRow, endCol, endRow, sheet):
    rangeSelected = []
    # Loops through selected Rows
    for i in range(startRow, endRow + 1, 1):
        # Appends the row to a RowSelected list
        rowSelected = []
        for j in range(startCol, endCol + 1, 1):
            rowSelected.append(sheet.cell(row=i, column=j).value)
        # Adds the RowSelected List and nests inside the rangeSelected
        rangeSelected.append(rowSelected)

    return rangeSelected


def renameFiles():
    print('Processing...')

    # Make a folder for the files
    current_directory = os.getcwd()
    folder_n_path = os.path.join(current_directory, folderDestination)
    print("Files saved to: " + folder_n_path)
    try:
        newFolder = os.makedirs(folder_n_path)

    except:
        print("Folder already exists")
        return

    # Get the Data to make the file names
    selectedRange = copyRange(1, 1, 2, 2, file_names_sheet)
    filesToFind = originalFilenameRange(3,1,3,2094,file_names_sheet)
    print(selectedRange)
    print(filesToFind)
    print (folderSource)

Everything is printing out correctly to this point, then with this loop it jumps to "file not found":

    for filename in os.listdir(folderSource):
        for i, filename in zip(selectedRange, os.listdir(folderSource)):
            filename = os.path.join(folderSource, filename)
            print (filename)
            if filename in filesToFind:
                file_name = i[0] + " " + i[1] + ".jpg"
                filename = os.path.join(folderSource, filename)
                file_name = os.path.join(folderDestination, file_name)
                shutil.copy(filename, file_name)
                print("Done")
            else:
                print ("File does not exist: " + filename)

go = renameFiles()
1

There are 1 best solutions below

2
On

It looks like filesToFind is a nested list based on your print(filesToFind) result. In your comparison line:

if filename in filesToFind:

You're comparing a string to a list within a list [['filename'], ['filename2'], ...] which always fails

What you want is to compare the filename string to a list of strings ['filename','filename2', ...]. Notice the subtle difference there?

Looking at your code, you are setting filesToFind here:

filesToFind = originalFilenameRange(3,1,3,2094,file_names_sheet)

So you would want to change your originalFilenameRange method to return a list of strings instead of a list of lists

A simple one-liner change to make your code work would be in this line in the originalFilenameRange method:

originalFilenameRange.append(rowSelected)

to this:

originalFilenameRange.append(rowSelected[0])