Sorting directory contents
Wolfgang Draxinger
wdraxinger at darkstargames.de
Tue Feb 20 09:26:53 EST 2007
Jussi Salmela wrote:
> I'm not claiming the following to be more elegant, but I would
> do it like this (not tested!):
>
> src_file_paths = dict()
> prefix = sourcedir + os.sep
> for fname in os.listdir(sourcedir):
> if match_fname_pattern(fname):
> fpath = prefix + fname
> src_file_paths[os.stat(fpath).st_mtime] = fpath
> for ftime in src_file_paths.keys().sort():
> read_and_concatenate(src_file_paths[ftime])
Well, both versions, mine and yours won't work as it was written
down, as they neglegt the fact, that different files can have
the same st_mtime and that <listtype>.sort() doesn't return a
sorted list.
However this code works (tested) and behaves just like listdir,
only that it sorts files chronologically, then alphabetically.
def listdir_chrono(dirpath):
import os
files_dict = dict()
for fname in os.listdir(dirpath):
mtime = os.stat(dirpath+os.sep+fname).st_mtime
if not mtime in files_dict:
files_dict[mtime] = list()
files_dict[mtime].append(fname)
mtimes = files_dict.keys()
mtimes.sort()
filenames = list()
for mtime in mtimes:
fnames = files_dict[mtime]
fnames.sort()
for fname in fnames:
filenames.append(fname)
return filenames
Wolfgang Draxinger
--
E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867
More information about the Python-list
mailing list