dir_lists = ["LUCKY1", "LUCKY2", "LUCKY3", "LUCKY4"] for dir_in in dir_lists: img_dir_root = os.path.join("C:/Users/JIA/Desktop/", dir_in) img_files = os.listdir(img_dir_root) img_files.sort(key=lambda x: int(x[:-4])) for file_name in img_files: num_img = int(file_name[:file_name.find('.')]) keystr = '{:0>3d}'.format(num_img) os.rename(os.path.join(img_dir_root, file_name), os.path.join(img_dir_root, keystr + ".jpg"))