Sorting directory contents
Wolfgang Draxinger
wdraxinger at darkstargames.de
Tue Feb 20 14:14:37 EST 2007
Larry Bates wrote:
> 3) You didn't handle the possibility that there is s
> subdirectory
> in the current directory. You need to check to make sure it
> is a file you are processing as os.listdir() returns files
> AND directories.
Well, the directory the files are in is not supposed to have any
subdirectories.
> 4) If you just put a tuple containing (mtime, filename) in a
> list
> each time through the loop you can just sort that list at
> the end it will be sorted by mtime and then alphabetically.
Ah, of course. Hmm, seems I was short of caffeine when I hacked
my code :-P
> def listdir_chrono(dirpath):
> import os
> #
> # Get a list of full pathnames for all the files in dirpath
> # and exclude all the subdirectories. Note: This might be
> # able to be replaced by glob.glob() to simplify. I would
> # then add a second optional parameter: mask="" that would
> # allow me to pass in a mask.
> #
> # List comprehensions are our friend when we are processing
> # lists of things.
> #
> files=[os.path.join(dirpath, x) for x in
> os.listdir(dirpath)
> if not os.path.isdir(os.path.join(dirpath, x)]
>
> #
> # Get a list of tuples that contain (mtime, filename) that
> # I can sort.
> #
> flist=[(os.stat(x).st_mtime, x) for x in files]
>
> #
> # Sort them. Sort will sort on mtime, then on filename
> #
> flist.sort()
> #
> # Extract a list of the filenames only and return it
> #
> return [x[1] for x in flist]
> #
> # or if you only want the basenames of the files
> #
> #return [os.path.basename(x[1]) for x in flist]
Now, THAT is elegant.
Wolfgang Draxinger
--
E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867
More information about the Python-list
mailing list