Sorting directory contents
Paul Rubin
http
Tue Feb 20 10:10:46 EST 2007
Wolfgang Draxinger <wdraxinger at darkstargames.de> writes:
> src_file_paths = dict()
> for fname in os.listdir(sourcedir):
> fpath = sourcedir+os.sep+fname
> if not match_fname_pattern(fname): continue
> src_file_paths[os.stat(fpath).st_mtime] = fpath
> for ftime in src_file_paths.keys().sort():
> read_and_concatenate(src_file_paths[ftime])
Note you have to used sorted() and not .sort() to get back a value
that you can iterate through.
Untested:
from itertools import ifilter
goodfiles = ifilter(match_fname_pattern,
(sourcedir+os.sep+fname for \
fname in os.listdir(sourcedir))
for f,t in sorted((fname,os.stat(f).st_mtime) for fname in goodfiles,
key=lambda (fname,ftime): ftime):
read_and_concatenate(f)
If you're a lambda-phobe you can use operator.itemgetter(1) instead of
the lambda. Obviously you don't need the separate goodfiles variable
but things get a bit deeply nested without it.
More information about the Python-list
mailing list