Python elegant way to sort numerically named directories

996 views Asked by At

I have a series of directories that are all named as floating point values, for example:

0
1
2
2.5
6
6.1
10

I would like to get last (highest) numbered directory. Using the sort() method on the directory names (which are string), I get 10 directly after 1.

dirs = os.listdir(path)
dirs.sort()

This gives the order:

0
1
10
2
2.5
6
6.1

I can put them into a list of floats by casting each to a float and then ordering the list, which solves the ordering problem. But then when I return the value of the string, I get 10.0, which is not the name of the directory. I need it to be exactly "10" (or whatever the last directory happens to be named).

Is there an elegant way to do this?

1

There are 1 answers

4
Jonas Schäfer On BEST ANSWER

You can use the key argument to sort:

dirs = os.listdir(path)
dirs.sort(key=float)

The key argument must be a callable, which will be called for each element in the list. The sorting then happens with respect to the value returned by the callable, without modifying the list items themselves.

In this case, we use float as a callable, which will return the floating point value represented by the strings passed to it.

Obviously, this blows up with strings which are no floats (ValueError), but this seems to be outside your problem scope.