Python - 将excel文件读入列表并重命名文件夹中的文件

问题描述 投票:0回答:1

我们有一个excel文件,包含2094行和3列结构,如下所示:

员工旧ID |员工姓名|员工新ID

007219 | John Doe 001234

最终结果是:John Doe 001234.jpg

我们有一个文件夹,其中包含员工照片标签的旧ID,我们想要阅读excel文件,然后使用新ID复制和重命名照片。

代码问题 - 它在复制并重命名第一张照片后停止。我认为我需要调整最后一个for循环,但我在如何让它迭代上画一个空白。

注意:我试图通过包含文件对话框folderSource来使代码变得灵活。另外,我是Python的新手,所以如果你看到通过各种方式清理代码的方法让我知道,我在代码中的注释中添加了一些问题:

import openpyxl
import os
import shutil
from tkinter import *
from tkinter import filedialog

root = Tk()
root.withdraw()

# File with file name data
# Add the file name
file_names = openpyxl.load_workbook(filedialog.askopenfilename())
# Add the sheet name - can you make this more flexible? 
file_names_sheet = file_names['piclist2']  

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

# New Folder Name - is there a filedialog way to flexibly create this?
folderDestination = 'SSL 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)

for i, filename in zip(selectedRange, os.listdir(folderSource)):
    print(filename)
    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()

我相信问题出现在最后一段代码中,但我无法弄清楚如何进行循环。思考?

python excel rename openpyxl shutil
1个回答
1
投票

试试你的最后一个循环,让我知道结果如何,可能需要进行一些修改,因为我看不到你的数据。看来你想在列表上一起运行for循环,所以试试这个:

for i, filename in zip(selectedRange, os.listdir(folderSource)):
    file_name = str(i[1]) + " " + i[2] + ".jpg"
    filename = os.path.join(folderSource, filename)
    file_name = os.path.join(folderDestination, file_name)
    shutil.copy(filename, file_name)
print(done)
go = renameFiles()

对于嵌套for循环结构,请考虑以下事项:

loop1 = ['a','b','c','d','e']
loop2 = ['f','g','h','i','j']
for i in loop1: # iterates through a,b,c,d,e
    print(i) #prints a,b,c,d,e
    for j in loop2: # compares all j objects of loop2 to i in loop 1:
        ij = i + j
        print(ij) # this will add all j's to each i

片段输出将添加所有j到i的每次迭代,然后移动到i的下一次迭代:

'af','ag','ah','ai','aj','bf','bg','bh','bi',bj'... etc

将2个列表压缩在一起(这是我在答案中所做的)将loop1中的每个元素与两个列表中相同索引处的loop2进行比较:

for i,j in zip(loop1,loop2):
    ij = i + j
    print(ij)

输出:

'af','bg','ch','di','ej'

当你对2个列表使用zip函数时,你唯一需要考虑的是,迭代只会发生在最短列表的末尾。因此,如果loop1和loop2的长度不相等,那么i + j将在较短的列表完成后停止。我希望这澄清了我所做的一些事情。

© www.soinside.com 2019 - 2024. All rights reserved.