The natsorted () function cannot be applied to lists with elements in the pathlib.Path format. Therefore, I made my own function for sorting in natural order.
The sorted () function is a function that sorts the elements of a list in lexicographical order. For example, when there is such a list
strs = ["dir/10", "dir/1", "dir/3" , "dir/24"]
If you write like this,
for s in sorted(strs):
print(s)
It becomes like this.
dir/1
dir/10
dir/24
dir/3
It's in dictionary order, so it's reasonable, but it's a bit unpleasant for humans.
On the other hand, the natsorted () function is a function that sorts the elements of a list in natural order (a module is required). If you write like this for the same list,
from natsort import natsorted
for s in natsorted(strs):
print(s)
It becomes like this.
dir/1
dir/3
dir/10
dir/24
This one fits nicely. The best natsorted () function!
For example, in the directory structure below,
dir
├ 1
├ 3
├ 10
└ 24
In this way, you can create a list in pathlib.Path format. If you look up the pathlib module, you can find a lot of explanations, so I will omit it.
import pathlib
paths = [p for p in pathlib.Path("./dir/").iterdir() if p.is_dir()]
Then, if you sort this in natural order,
from natsort import natsorted
for p in natsorted(paths):
print(p)
It becomes like this.
dir\1
dir\10
dir\24
dir\3
** It's in dictionary order! ** ** Well, I'm sure it doesn't support the Path format. So if you read it in dictionary order and it's just that. Does it mean that the element must be str or int (I don't understand this area well. I want information).
I made my own function like this. The sorted () function makes use of the fact that key can be specified as an argument.
def paths_sorted(paths):
return sorted(paths, key = lambda x: int(x.name))
If you use this like this,
for p in paths_sorted(paths):
print(p)
It becomes like this.
dir\1
dir\3
dir\10
dir\24
The desired result was obtained.
In my case, the directory name was a numerical value, so I converted the directory name to an int and used it as a key. If you want to include a string like no1, no2 ..., you can use natsorted () as str (although you need a module). The same method should be applicable to files instead of directories.
Recommended Posts