'How to find files whose name is not exact in python
I created a script to find the images that have the codes that are in an excel file and copy them to another folder.
For example in my excel file I have 1856.jpg, 532.jpg and so on. In the folder that I specify, I have those images and up to that point the program works and copies what is in the excel file.
The problem comes when in my excel file there is an image 674.jpg so I have it in my folder but in this way 456_674_542.jpg I mean in a single photo there are 3 codes, how do I do it in that case?
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!")
Solution 1:[1]
Easiest way would be to just call find (returns the index of the searched pattern):
file_name = "456_674_542.jpg"
file_name_in_excel = "674"
if file_name.find(file_name_in_excel) != -1:
print(file_name)
If you need more special cases use regex.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PlzBePython |
