I have a folder with images.
I added to a list the paths for each image. They are not alphabetically sorted.
I made this function to sort but I the result it's the same when I print the list after sorting.
import os
import glob
images_path = os.path.expanduser('~\\Desktop\\samples\\')
def img_path_list():
img_list = []
for file_path in glob.glob(str(images_path) + "*.jpg"):
img_list.append(file_path)
img_list.sort(key=lambda x: str(x.split('.')[0]))
return img_list
print(img_path_list())
The result it's still i.e: [Desktop\\t0.jpg, Desktop\\t1.jpg, Desktop\\t10.jpg, Desktop\\t11.jpg, Desktop\\t2.jpg, ...]
EDIT: not a duplicate as long as I didn't request to use natsort module but with simple python.
解决方案
Using os.path.basename and assuming your filenames are all of the format X#.jpg with X a single character:
import os
img_list = ['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
'Desktop\\t10.jpg', 'Desktop\\t11.jpg',
'Desktop\\t2.jpg']
img_list.sort(key=lambda x: int(os.path.basename(x).split('.')[0][1:]))
print(img_list)
['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
'Desktop\\t2.jpg', 'Desktop\\t10.jpg',
'Desktop\\t11.jpg']
With a named function to illustrate how lambda works:
def sorter(x):
return int(os.path.basename(x).split('.')[0][1:])
img_list.sort(key=sorter)
Explanation
There are a few steps here:
Extract the filename via os.path.basename.
Split by . and extract first element.
Then slice by 1st character onwards.
Convert the result to int for numerical ordering.