Sorting directory contents
Jussi Salmela
tiedon_jano at hotmail.com
Tue Feb 20 10:24:44 EST 2007
Wolfgang Draxinger kirjoitti:
> 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
More elegant or not ... I did it MY WAYYYY!!! (and tested this time
really carefully;)):
#-------------------------------
def listdir_chrono_2(dirpath):
import os
files_dict = {}
prefix = dirpath + os.sep
for fname in os.listdir(dirpath):
mtime = os.stat(prefix + fname).st_mtime
files_dict.setdefault(mtime, []).append(fname)
mtimes = sorted(files_dict.keys())
filenames = []
for mtime in mtimes:
filenames += sorted(files_dict[mtime])
return filenames
firstLst = listdir_chrono('.')
secondLst = listdir_chrono_2('.')
if firstLst == secondLst: print 'OK'
else: print 'ERROR!!!'
#-------------------------------
I keep taking the "dirpath + os.sep" part out of the loop because it is
a loop invariant and doesn't have to be inside the loop.
Cheer
More information about the Python-list
mailing list