I've generated many image-files (PNG) within a folder. Each have names akin to "img0.png", "img1.png", ..., "img123164971.png" etc. The order of these images matter to me, and the numerical part represent the order I need to retrieve them before I add them to a html-form.
This question closely gives me a solution: Does Python have a built in function for string natural sort?
But I'm not entirely sure how to incorporate it into my specific code:
imagedata = list()
files_and_dirs = Path(imagefolder).glob('**/*')
images = [x for x in files_and_dirs if x.is_file() and x.suffix == '.png']
for image in images:
imagedata.append("<img src='{0}/{1}' width='200'>".format(imagefolder, image.name))
These files are naturally read alphanumerically, but that is not what I want. I have a feeling that I can simply do a images = sort_function(images), but I'm unsure how exactly. I realize I can do this:
imagedata = list()
files_and_dirs = Path(barcodeimagefolder).glob('**/*')
images = [x.name for x in files_and_dirs if x.is_file() and x.suffix == '.png']
images = natural_sort(images)
for image in images:
imagedata.append("<img src='{0}/{1}' width='200'>".format(imagefolder, image))
def natural_sort(l):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
Using Mark Byers' solution in the link. But I later on need the list of the actual images themselves, and it seems redundant having two lists when one of them contains all the data in the other. Instead I would very much like to sort the list of image-files based on their file-name, in that way. Or better yet, read them from the folder in that order, if possible. Any advice?
Edit: I changed the title, making it a bit more condense and hopefully still accurate.