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}"))
8
  • What is the error? Commented Jan 6, 2022 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. Commented Jan 6, 2022 at 11:47
  • There is no error, we want the files to be accessed in a sorted manner. Its accessing it randomly. @OrangoMango Commented Jan 6, 2022 at 11:47
  • 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. Commented Jan 6, 2022 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. Commented Jan 6, 2022 at 12:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.