我们有一个包含2094行和3列的excel文件,其结构如下:
Employee Old ID | Employee Name | Employee New ID
007219 | John Doe | 001234
The end result being: 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()
我相信问题出在最后一段代码中,但我不知道如何执行循环。思想?在
在最后一个循环中尝试一下,让我知道结果如何,因为我看不到您的数据,所以可能需要进行一些修改。您似乎希望同时对列表运行for循环,因此请尝试以下操作:
对于嵌套For循环结构,请考虑以下事项:
^{pr2}$在转到下一个i迭代之前,snippet输出将向i的每次迭代添加所有j:
^{3}$将2个列表压缩在一起(这是我在回答中所做的)将loop1和loop2中的每个元素在两个列表中的相同索引处进行比较:
输出:
在对2个列表使用zip函数时,唯一需要考虑的是迭代只会发生在最短列表的末尾。因此,如果loop1和loop2的长度不相等,那么i+j将在短列表完成后停止。我希望这能澄清我所做的一些事情。在
相关问题 更多 >
编程相关推荐