Process files in order

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Jul 27 17:17:00 EDT 2006


Khoa Nguyen a écrit :
> Hi,
> 
> I have a requirement to process all files in a directory in
> chronological order.

Access time, modification time ? Ascending, descending ?-)

> The os.listdir() function, however, lists the
> files in random order. Is there a similar function in Python that
> allows me to specify the listing order (like ls -t for example)?

Not AFAIK. But os.path.get[acm]time(<filename>) and sorted() may help:

from os.path import getmtime, join, isfile
from os import listdir, getcwd

listfiles = lambda p: filter(isfile, # only list files
                              map(lambda f, p=p : join(p,f),
                                  listdir(p)))

files = listfiles(getcwd())
sortedfiles = map(lambda item: item[1],
                   sorted(zip(map(getmtime, files), files)))


You can apply reversed() to sortedfiles if you want them in reversed order.


HTH



More information about the Python-list mailing list