0

We want the png files to be accessed as 15.png,45.png,75.png and so on. This is the code and the output we are getting

current output

import os
keypts_labels=[]
class_list=os.listdir('dataset')
for name in class_list:
    for image in os.listdir(f"dataset/{name}"):
        for item in os.listdir(f"dataset/{name}/{image}"):
            print(os.path.abspath(f"dataset/{name}/{image}/{item}"))
martineau
  • 119,623
  • 25
  • 170
  • 301
  • What is the error? – Paul Kocian Jan 06 '22 at 11:44
  • I think they want the numbers to be sorted be like 15.png 20.png 50.png . I think you can use sort on the list but I assume that didn't work. – Batselot Jan 06 '22 at 11:47
  • There is no error, we want the files to be accessed in a sorted manner. Its accessing it randomly. @OrangoMango – Radha Mujumdar Jan 06 '22 at 11:47
  • Directory or file names are strings not numbers. So they are sorted lexically. If you want them to sort as per the numerical value of name, then you need to sort them yourself . – Kris Jan 06 '22 at 11:47
  • Yes, tried using sort. But didn't work @Batselot – Radha Mujumdar Jan 06 '22 at 11:47
  • I can't reproduce this from the code sample you have given. Can you share where you get the items from? From your code I assume sorting items would be the key to the solution . – Batselot Jan 06 '22 at 11:49
  • 1
    They seem to be in lexicographic order, which is what I would expect. If you want them in any other order, you need to sort them using a custom key. See the [dupe target](https://stackoverflow.com/q/5967500/3890632). – khelwood Jan 06 '22 at 12:04
  • 1
    The values returned from `listdir()` are not defined to be in any particular order. If you want them in some particular order, you will need to sort them yourself. – martineau Jan 06 '22 at 12:38

1 Answers1

1

You don't need to handle all this iterating logic, when there are easy ways to do it. See the approach below

def list_files(from_folder):
    from glob import glob
    import pathlib
    # Use glob to get all files in the folder, based on the type
    png_files = glob(f"{from_folder}/**/*.png", recursive=True)
    # Use a numerical sort, using the file name prefix as the key
    png_files = sorted(png_files, key=lambda path: int(pathlib.Path(path).stem))
    
    print(png_files) #return it if you want

list_files("dataset")

This piece of function will actually list what you need. This assumes, all png files has the name a valid number, and you are searching only for png files.

I hope the logic is understood from the comments itself.

Kris
  • 8,680
  • 4
  • 39
  • 67