Sorting directory contents
Rob Wolfe
rw at smsnet.pl
Tue Feb 20 10:27:10 EST 2007
Wolfgang Draxinger wrote:
> 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
Using the builtin functions `sorted`, `filter` and the `setdefault`
method of dictionary could a little shorten your code:
def listdir_chrono(dirpath):
import os
files_dict = {}
for fname in filter(os.path.isfile, os.listdir(dirpath)):
mtime = os.stat(os.path.join(dirpath, fname)).st_mtime
files_dict.setdefault(mtime, []).append(fname)
filenames = []
for mtime in sorted(files_dict):
for fname in sorted(files_dict[mtime]):
filenames.append(fname)
return filenames
--
HTH,
Rob
More information about the Python-list
mailing list