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

时间:2018-09-07 19:28:28

标签: python excel rename openpyxl shutil

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

  

员工旧身份证|员工姓名|员工新编号

     

007219 |约翰·杜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()

我相信问题出在代码的最后一部分,但是我无法弄清楚如何执行循环。有想法吗?

1 个答案:

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

摘要输出将在i的每次迭代之前将所有j添加到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将在较短的列表完成后停止。我希望这可以澄清我所做的一些事情。