If you want to sort the path naturally (sort according to the numbers), you can put a lambda expression in key
as shown below.
natsorted(list(pathlib.Path(path).glob("*")),key=lambda x:x.name)
The following digression
It was necessary to sort the image data when converting a large number of images to PDF. The name of the image file looks like this.
1.jpg
200.jpg
12.jpg
...
I want to sort them according to the numbers, so I want to sort them naturally instead of sorting them in a dictionary.
When I got it with pathlib
and sorted it with natsort
, it looked like this.
PosixPath('/Users/usrname/images/1.jpg'),
PosixPath('/Users/usrname/images/10.jpg'),
PosixPath('/Users/usrname/images/20.jpg'),
...
No, please work with natsort
. I thought, but it doesn't seem to sort if it's path. However, the countermeasures were written firmly in the reference.
Excerpt from natsort reference.py
>>> a = ['apple2.50', '2.3apple']
>>> natsorted(a, key=lambda x: x.replace('apple', ''), alg=ns.REAL)
['2.3apple', 'apple2.50']
It seems good to specify key
in the same way as sort
. The file name to be sorted is thrown. This is well written in the pathlib
reference,
Excerpt from pathlib reference.py
>>> PurePosixPath('my/library/setup.py').name
'setup.py'
In other words, .name
can take the end of path. If you use them in combination, you can sort them.
The formula is omitted because it is at the beginning. When I tried using it, it looked like this.
PosixPath('/Users/usrname/images/1.jpg'),
PosixPath('/Users/usrname/images/2.jpg'),
PosixPath('/Users/usrname/images/3.jpg'),
...
It was sorted well. Congratulations
Recommended Posts