0

非常感谢@d_kennetz让我的代码恢复到当前状态,但我一直在碰壁。

代码将一个excel文件读入一个列表,然后遍历一个文件夹并重命名文件,但它按列表的顺序执行此操作,然后从第一个文件开始并工作到最后一个,所以如果我手动排序excel列表和文件本身我可以准确地重命名它们但我想在循环中添加一个 find() 以便我可以使这个程序更灵活。

目标 - 添加 find() 以便循环遍历当前文件名列表(在 excel 中),然后在所选文件夹中找到正确的文件,然后将其重命名为正确的新名称。

当前工作代码(没有 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()

我尝试添加 if() 的代码,但它只是说:“找不到文件”

# 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'

添加这个以循环原始文件名列并添加到列表中:

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)

到目前为止,一切都正确打印出来,然后通过这个循环跳转到“找不到文件”:

    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()
4

1 回答 1

1

它看起来像是filesToFind一个基于您的print(filesToFind)结果的嵌套列表。在您的比较行中:

if filename in filesToFind:

您正在将字符串与列表中的列表进行比较,该列表[['filename'], ['filename2'], ...]总是失败

您想要的是将filename字符串与字符串列表进行比较['filename','filename2', ...]。注意到那里的细微差别了吗?

查看您的代码,您正在filesToFind此处设置:

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

因此,您可能希望更改originalFilenameRange方法以返回字符串列表而不是列表列表

使您的代码工作的简单的单行更改将在该originalFilenameRange方法的这一行中:

originalFilenameRange.append(rowSelected)

对此:

originalFilenameRange.append(rowSelected[0])
于 2018-09-18T19:01:10.750 回答