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?
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