我创建了一个脚本来查找excel文件中包含代码的图像,并将它们复制到另一个文件夹中。
例如,在我的excel文件中,我有1856.jpg、532.jpg等等。在我指定的文件夹中,我拥有这些图像,到那时为止,程序可以工作并复制excel文件中的内容。
问题来了,当我的excel文件中有一个图像674.jpg,所以我把它放在文件夹中,但这样456_674_542.jpg我的意思是,在一张照片中有3个代码,在这种情况下我该怎么做?
import os, shutil, xlrd
#We create an empty list to fill with the codes later
files_to_find = []
lista_imagenes_total=[]
ruta_destino = 'C:/Users/Albin Rodriguez/Pictures/carpeta4'
#We open the excel file and fetch all the codes to the list.
data = xlrd.open_workbook(input("Digite el nombre del archivo excel y su extension: "))
sheet1 = data.sheet_by_index(0)
for i in range(sheet1.nrows):
files_to_find.append(sheet1.cell_value(i, 0))
#we search the images in this path
for root, dirs, files in os.walk('C:/Users/Albin Rodriguez/Desktop/FOTOS PRODUCTOS/'):
for _file in files:
if _file in files_to_find:
print (f'{_file} Encontrado en esta ruta: ' + str(root)) # If we find it, this will print the path
shutil.copy(os.path.abspath(root + '/' + _file), 'C:/Users/Albin Rodriguez/Pictures/carpeta4')
lista_imagenes_total.append(_file)
#We check which files were not found
for elementos in files_to_find:
if elementos not in lista_imagenes_total:
print(f"El archivo {elementos} no fue encontrado!")
最简单的方法是只调用find(返回搜索模式的索引(:
file_name = "456_674_542.jpg"
file_name_in_excel = "674"
if file_name.find(file_name_in_excel) != -1:
print(file_name)
如果您需要更多特殊情况,请使用regex。