I want to get a list of PosixPath objects and have it sorted based on the corresponding file sizes. I am trying to to this using sorted function. The key that I want to use for sorting is object.stat().st_size
, where object is an PosixPath object, stat()
returns an os.stat_result
object, and st_size
is the size of the file corresponding to the PosixPath object. I know how to sort based on either an object method or an object attribute using operator.methodcaller
or operator.attrgetter
, but I can't figure out how to use an attribute of the object returned by methodcaller
.
I tried the following and some variations but it does not work:
from operator import attrgetter, methodcaller
from pathlib import Path
sorted(Path('my_directory').glob('*.extension'), key=methodcaller('stat').st_size)