Sort files after glob in Pathlib
The data of all my sensor is stored in csv files. Today I wanted to create a dashboard showing the newest value of some sensors. Especially the current CO2 value is interesting here - to see when fresh air would be a good idea.
So I experimented with glob
in pathlib to get the newest file for a sensor.
>>> from pathlib import Path >>> >>> # this returns an unordered list - not helpful here >>> list(Path(".").glob("**/*SCD30.csv"))[0] PosixPath('2021/07/24/2021-07-24_SCD30.csv') >>> >>> # sorted sorts by folder/filename. this works fine if the filenames are sortable >>> sorted(Path(".").glob("**/*SCD30.csv"))[-1] PosixPath('2022/02/09/2022-02-09_SCD30.csv') >>> >>> # reverse the sorting to get the newest on top >>> sorted(Path(".").glob("**/*SCD30.csv"), reverse=True)[0] PosixPath('2022/02/09/2022-02-09_SCD30.csv') >>> >>> # sort by modified and get the newest first >>> sorted(Path(".").glob("**/*SCD30.csv"), key=lambda x: x.stat().st_mtime, reverse=True)[0] PosixPath('2022/02/09/2022-02-09_SCD30.csv') >>>
For my dashboard code the filename based sorting is good enough but good to know that the modified time solution could handle a more chaotic folder structure.