How to get a directory list sorted by date?
Peter Otten
__peter__ at web.de
Sun May 15 09:03:03 EDT 2016
Tim Chase 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 mentioned it because it avoids the duplicate stat call of the older
approach which is rather inelegant.
Taking another look at the OP's problem I think sorting could be entirely
avoided. Instead have the memory card remember when its data was last
archived. Pseudo-code:
try:
cut_off = load_cut_off(memory_card)
pics = (pic for pic in memory_card if gettime(pic) > cut_off)
except:
pics = memory_card
for pic in pics:
copy_to_archive(pic)
save_cut_off(now(), memory_card)
As long as computer and camera time are in sync...
More information about the Python-list
mailing list