Sorting directory contents

Jussi Salmela tiedon_jano at hotmail.com
Tue Feb 20 09:22:22 EST 2007


Wolfgang Draxinger kirjoitti:
> H folks,
> 
> I got, hmm not really a problem, more a question of elegance:
> 
> In a current project I have to read in some files in a given
> directory in chronological order, so that I can concatenate the
> contents in those files into a new one (it's XML and I have to
> concatenate some subelements, about 4 levels below the root
> element). It all works, but somehow I got the feeling, that my
> solution is not as elegant as it could be:
> 
> 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])
> 
> of course listdir and sorting could be done in a separate
> function, but I wonder if there was a more elegant approach.
> 
> Wolfgang Draxinger

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])


Cheers,
Jussi



More information about the Python-list mailing list