How to get a directory list sorted by date?
Chris Angelico
rosuav at gmail.com
Sun May 15 07:59:53 EDT 2016
On Sun, May 15, 2016 at 9:15 PM, Tim Chase
<python.list at tim.thechases.com> wrote:
> On 2016-05-15 11:46, Peter Otten wrote:
>> def sorted_dir(folder):
>> def getmtime(name):
>> path = os.path.join(folder, name)
>> return os.path.getmtime(path)
>>
>> return sorted(os.listdir(folder), key=getmtime, reverse=True)
>>
>> The same idea will work with pathlib and os.scandir():
>>
>> def _getmtime(entry):
>> return entry.stat().st_mtime
>>
>> def sd_sorted_dir(folder):
>> return sorted(os.scandir(folder), key=_getmtime, reverse=True)
>
> unless sorted() returns a lazy sorter, you lose most of the advantages
> of scandir() being lazy since you have to read the entire directory
> list into memory to sort it.
I'm not sure a lazy sorter exists. You can't know which is the
oldest/newest file in a directory without knowing all their mtimes.
ChrisA
More information about the Python-list
mailing list