2

I have some images which I generate from url with random pictures. Then I try to sort them to work with it properly, but they sorting is messed up. Appreciate any advices or pointing to what I missing

Code ( image list generating ):

def image_downloader():

    image_url = 'url'

    for count in tqdm(range(20)):
        image_data = requests.get(image_url).content

        with open(f'image_{count}.jpg', 'wb') as handler:
            handler.write(image_data)

        sleep(0.5)

And my sorting ( trying to get it by generated picture "id" ):

local_folder_content = os.listdir('.')

images_list = list((image for image in local_folder_content if image.endswith('.jpg')))

pprint((sorted(images_list, key=lambda x: x[:-4].split('_')[1])))

Result( sorting is messed up) :

['image_0.jpg',
 'image_1.jpg',
 'image_10.jpg',
 'image_11.jpg',
 'image_12.jpg',
 'image_13.jpg',
 'image_14.jpg',
 'image_15.jpg',
 'image_16.jpg',
 'image_17.jpg',
 'image_18.jpg',
 'image_19.jpg',
 'image_2.jpg',
 'image_3.jpg',
 'image_4.jpg',
 'image_5.jpg',
 'image_6.jpg',
 'image_7.jpg',
 'image_8.jpg',
 'image_9.jpg']
Yevhen_Radchenko
  • 965
  • 8
  • 15

2 Answers2

2

You can try something like this :

images_list.sort(key= lambda i: int(i.lstrip('image_').rstrip('.jpg')))
merieme
  • 191
  • 7
1

You have to generate all filenames with two (or more) digits:

with open(f'image_{str(count).zfill(2)}.jpg', 'wb') as handler:

Output:

image_01.jpg
image_02.jpg
image_04.jpg

In this case your images will be correctly sorted.

Alderven
  • 7,569
  • 5
  • 26
  • 38
  • If i generate more than 100 images it still get wrong sequence `['image_00.jpg', 'image_01.jpg', 'image_02.jpg', 'image_03.jpg', 'image_04.jpg', 'image_05.jpg', 'image_06.jpg', 'image_07.jpg', 'image_08.jpg', 'image_09.jpg', 'image_10.jpg', 'image_100.jpg', 'image_101.jpg', 'image_102.jpg', 'image_103.jpg', 'image_104.jpg', 'image_105.jpg', 'image_106.jpg', 'image_107.jpg', 'image_108.jpg', 'image_109.jpg', 'image_11.jpg',` – Yevhen_Radchenko Feb 27 '19 at 20:04
  • Change `zfill(2)` to `zfill(4)` and it will generates you `image_0001.jpg` – Alderven Feb 27 '19 at 20:08