Search code examples
listpython-2.7xlrd

Bulk Search/replacing of filenames using python


I have:

  1. An excel file as A1:B2.
  2. A folder with 200 jpeg files.

I'm trying to search the filename in the folder with the value in Column A and replace it with the value in Column B if found without changing the extensions of the files in the folder.

Here am stuck using various skiddies to do this but failed. Here's my code:

import os
import xlrd
path = r'c:\users\c_thv\desktop\x.xls'
#collect the files in fexceler
path1 = r'c:\users\c_thv\desktop'
data = []
for name in os.listdir(path1):
  if os.path.isfile(os.path.join(path1, name)):
    fileName, fileExtension = os.path.splitext(name)
     if fileExtension == '.py':
       data.append(fileName)
#print data
#collect the filenames for changing
book = xlrd.open_workbook(path)
sheet = book.sheet_by_index(0)
cell = sheet.cell(0,0)
cells = sheet.row_slice(rowx=0,start_colx=0,end_colx=2)
excel = []
#collect the workable data in an list
for cell in cells:
  excel.append(cell) 
#print excel
#compare list for matches
for i,j in enumerate(excel):
  if j in data[:]:
    os.rename(excel[i],data[i])

Solution

  • Try a print "Match found" after if j in data[:]: just to check if the condition is ever met. My guess is there will be no match because the list data is full on python filemanes (if fileExtension == '.py') and you are looking for jpeg files in the excel list. Besides, old is not defined.

    EDIT:

    If I understand correctly, this will may help:

    import os, xlrd
    
    path = 'c:/users/c_thv/desktop' #path to jpg files
    path1 = 'c:/users/c_thv/desktop/x.xls'
    
    data =[] #list of jpg filenames in folder
    
    #lets create a filenames list without the jpg extension
    for name in os.listdir(path):
        fileName, fileExtension = os.path.splitext(name)
        if fileExtension =='.jpg':
            data.append(fileName)
    
    
    #lets create a list of old filenames in the excel column a
    
    book = xlrd.open_workbook(path1)
    sheet = book.sheet_by_index(0)
    oldNames =[]
    for row in range(sheet.nrows):
        oldNames.append(sheet.cell_value(row,0))
    
    
    #lets create a list with the new names in column b
    newNames =[]
    for row in range(sheet.nrows):
        newNames.append(sheet.cell_value(row,1))
    
    
    #now create a dictionary with the old name in a and the corresponding new name in b
    
    fileNames = dict(zip(oldNames,newNames))
    
    print fileNames
    
    #lastly rename your jpg files
    
    for f in data:
        if f in fileNames.keys():
            os.rename(path+'/'+f+'.jpg', path+'/'+fileNames[f]+'.jpg')