Chronological Processing of Files

George Sakkis gsakkis at rutgers.edu
Thu Sep 22 03:21:28 CEST 2005


"Peter Hansen" <peter at engcorp.com> wrote:

> yoda wrote:
> > This feels like a stupid question but I'll ask it anyway.
> >
> > How can I process files chronologically (newest last) when using
> > os.walk()?
>
> Do you want the ordering to apply just to files within each directory,
> or to all the files found (recursively) during the entire walk?  Define
> "newest" (most recent modified date or something else?).  Is there any
> reason why sorting with the results of os.access().st_mtime as the key
> is not possible or sufficient?
>
> -Peter

You can make your life easier using the non-standard (yet ?) path module:

from path import path

top = path('.')
sort_kwds = dict(key=path.mtime.__get__, reverse=True)

# sort all files together
sorted_all = sorted(top.walkfiles(), **sort_kwds)

# sort files by directory

sorted_by_dir = sorted(top.files(), **sort_kwds) \
                         + sum((sorted(dir.files(), **sort_kwds)
                                    for dir in path(top).walkdirs()), [])

George





More information about the Python-list mailing list