0

I have more than 1000 JPG images in a folder having different name. I want to rename images as 0.JPG, 1.jpg, 2.jpg...

I tried different code but having below error:

The system cannot find the file specified: 'IMG_0102.JPG' -> '1.JPG'

The below code is one the codes found in this link: Rename files sequentially in python

import os
_src = "C:\\Users\\sazid\\Desktop\\snake"
_ext = ".JPG"
for i,filename in enumerate(os.listdir(_src)):
    if filename.endswith(_ext):
        os.rename(filename, str(i)+_ext)

How to solve this error. Any better code to rename image files in sequential order?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • In `os.rename(filename,...` it's looking for the filename in the working directory (the directory you're running the script in). Change that part to `os.rename(os.getcwd() + filename,...` – pythomatic Sep 04 '20 at 17:50
  • @SazidaBintaIslam if you found a solution mark the correct answer or close the question – Oleg Vorobiov Sep 07 '20 at 18:11

2 Answers2

1

os.listdir only returns the filenames, it doesn't include the directory name. You'll need to include that when renaming. Try something like this:

import os
_src = "C:\\Users\\sazid\\Desktop\\snake"
_ext = ".JPG"
for i,filename in enumerate(os.listdir(_src)):
    if filename.endswith(_ext):
        src_file = os.path.join(_src, filename)
        dst_file = os.path.join(_src, str(i)+_ext)
        os.rename(src_file, dst_file)
mattficke
  • 727
  • 4
  • 9
0

just use glob and save yourself the headache

with glob your code turns into this:

import os
from glob import glob

target_dir = './some/dir/with/data'

for i, p in enumerate(glob(f'{target_dir}/*.jpg')):
    os.rename(p, f'{target_dir}/{i}.jpg')

in this code glob() gives you a list of found file paths for files that have the .jpg extension, hence the *.jpg pattern for glob, here is more on glob

Oleg Vorobiov
  • 482
  • 5
  • 14