Python-添加查找和替换语句

时间:2018-09-18 17:23:50

标签: python excel filenames batch-rename find-replace

非常感谢@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()

1 个答案:

答案 0 :(得分: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])