0

I have 100 images in a folder and I want to rename all of them. For example, Car.1.jpg, Car.2.jpg,Car.3.jpg so on and save them into another folder. I wrote the code which renames all the images as I want but it saves in the same folder which images exist. I want to rename all images and keep the original image name in the directory and copy renamed images into another directory.

import os
from tqdm import tqdm

path = './training_data/car/'

def image_rename():
    cnt = 1
    for img in tqdm(os.listdir(path)):
        if os.path.isfile(path+img):
            filename, file_extention = os.path.splitext(path+img)
            os.rename(os.path.join(path, img), os.path.join(path, 
                       str('car.') + str(cnt) + file_extention))
       cnt +=1

image_rename()

2 Answers2

2

You should try using shutil.move()

import shutil
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
diegoiva
  • 454
  • 1
  • 8
  • 17
  • Its moving after rename, I dont want to move my images after rename. I mean, I want to keep my images and names in the folder and copy images into another folder with the name which i want –  Mar 28 '18 at 16:04
  • 2
    Found the answer, I had to use shutil.copy("path/to/current/file.foo", "path/to/new/destination/for/file.foo") –  Mar 28 '18 at 16:12
1

Add a variable output_path pointing to the folder to which you want to export the files, then use this variable in the seconde argument of os.rename(), like this :

import os
from tqdm import tqdm

path = './training_data/car/'
output_path = './training_data/output_folder/'

def image_rename():
    cnt = 1
    for img in tqdm(os.listdir(path)):
        if os.path.isfile(path+img):
            filename, file_extention = os.path.splitext(path+img)
            os.rename(os.path.join(path, img), os.path.join(output_path, 
                       str('car.') + str(cnt) + file_extention))
       cnt +=1

image_rename()

Make sure to create the output folder in your system (by using mkdir, for example).

D. LaRocque
  • 397
  • 5
  • 16
  • I did this one before, but my problem is after rename, all my images move to output_path. I want to keep my images and their name in the folder which exists and rename images into another folder –  Mar 28 '18 at 16:02