os.listdir not accessing numerically labelled files in ascending order

271 Views Asked by At

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}"))
1

There are 1 best solutions below

0
On

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.