user11409134
user11409134

Reputation: 79

How to rename all the images in a directory with name coming from an excel cell values?

I have a folder with images that are currently named with some random image numbers. I want to rename all the images in the directory with a specific column of an excel sheet which I put on a data frame.

Note: The random number of images is the last part of the excel value. For example, if an image name in the folder is 'img1097' then in the excel sheet I can find the image in the column as 'First_Second_img1097'. So in the folder, I have images with names like 'img1098', 'img1099' etc, and in the data frame, I have values like as follows:

#my_dataframe

**Column**

First_Second_img1097

Table_Chairs_img1098

Cat_Image_img1099

I have been trying to implement different options with no luck. Here is my code:

    import os,re
    path = r'myfolder\user\allimages\Main\target'
    files = os.listdir(path)
    for index, file in enumerate(files):
        tempname = file.split('.')[0] #no extentions
        for i in tempname :
             for picture_name in my_dataframe['Column']:
                     if temp_file_name == picture_name:
                          os.rename(os.path.join(path, file),                             
                          os.path.join(path,str(index) + '.jpg'))

I'm expecting an answer where I will be able to rename all the matching images with the cell values of the dataframe's "column" column. so 'img1097' should be renamed with 'First_Second_img1097'. Hope this makes it clear.

Upvotes: 0

Views: 1313

Answers (2)

ALFAFA
ALFAFA

Reputation: 648

To rename all image files in your directory, you can try the following python program. Just run the python script and the files will be automatically renamed corresponding to excel cell values:

import pandas as pd
import xlrd
import os
import glob

# Your directory
mydir = (os.getcwd()).replace('\\','/') + '/'

# Get data of cells from excel
df=pd.read_excel(r''+ mydir +'test.xlsx')
for i in range(len(df['Name'])):
    print( df['Name'][i])
number_of_cell=len(df['Name'])

# Get the list of specified files in a directory
filelist=os.listdir(mydir)
for file in filelist[:]: # filelist[:] makes a copy of filelist.
    if not(file.endswith('.png') or file.endswith('.jpg')):
        filelist.remove(file)
print (filelist)
number_of_files=len(filelist)

# Rename all files in directory with a value of cell in excel
for i in range(number_of_files):
    os.rename(mydir+ filelist[i], mydir+ df['Name'][i] + '.' + os.path.splitext(filelist[i])[1][1:])

print ('Success')

This is the excel file: excel file

The file name of all images before and after: files before it were named

files after being renamed

==== EDITED ====

import pandas as pd
import xlrd
import os
import glob

# Your directory
mydir = (os.getcwd()).replace('\\','/') + '/'

# Get data of cells from excel
df=pd.read_excel(r''+ mydir +'Book1.xlsx')
for i in range(len(df['New_Image_Name'])):
    print( df['New_Image_Name'][i])
number_of_cell=len(df['New_Image_Name'])

# Get the list of specified files in a directory
filelist=os.listdir(mydir)
for file in filelist[:]: # filelist[:] makes a copy of filelist.
    if not(file.endswith('.png') or file.endswith('.jpg')):
        filelist.remove(file)
print (filelist)
number_of_files=len(filelist)

# Rename all files in directory with a value of cell in excel
# Files will be ranamed with cell value if the digits of last name of file is matched with the last digits in excel cell
for i in range(number_of_files):
    for n in range(number_of_cell):
        if ((((df['New_Image_Name'][n].split('_'))[len((df['New_Image_Name'][n].split('_')))-1]).split('.'))[0] == (((filelist[i].split('_'))[len((filelist[i].split('_')))-1]).split('.'))[0]):
            os.rename(mydir+ filelist[i], mydir+ df['New_Image_Name'][n] + '.' + os.path.splitext(filelist[i])[1][1:])
            break

print ('Success')

The file name of all images before and after:

files before it were named

The file after being renamed Hope this can help you. Have a nice day.

Upvotes: 1

Rahul Agarwal
Rahul Agarwal

Reputation: 4100

This will solve your problem:

import ntpath
import os,re

path = r'myfolder\user\allimages\Main\target'
pathlist = []
for root, dirs, files in os.walk(path):
    for name in files:
        pathlist.append(os.path.join(root, name))

for new_path in pathlist:
    file_name = ntpath.basename(new_path)
    tempname = file_name.split('.')[0] 
    for index, row in df["Columns"].iteritems(): 
        new_row = row.split('_')[-1] ## Gives img1097
        new_tempname = tempname.replace(" ", "") ## makes img 1097 to img1097
        if new_row == new_tempname: ## Now the matching will work
            os.rename(os.path.join(path, file_name), os.path.join(path, str(row)+'.jpg'))

Upvotes: 1

Related Questions