[Tutor] sorting os.listdir.
Gerrit Holl
gerrit@nl.linux.org
Thu May 15 08:13:02 2003
Hi Thomas,
Thomas CLive Richards schreef op donderdag 15 mei om 14:00:05 +0000:
> IS there a reason os.listdir doesn't sort it's output? It does seem a little silly.
It is not necessary, and sometimes it may take a lot of resources.
Imagine listing the contents of a very large directory: sorting
approx. 10.000 filenames may be very time-consuming.
> this function will call os.listdir, and then sort through the output, according to the sort parameter. possible sort parameters should include alphanumeric, numeric, ascii (just takes the ascii values of the charecter).
You may want to use cmp for that. It may be better to pass a function
as second argument, like a default list sort does.
Your code may look like (UNTESTED):
def sortedlistdir(d, cmpfunc=cmp):
l = os.listdir(d)
l.sort(cmpfunc)
return l
> hmmm.. isn't there some sort of builtin sort() function somewhere?? only it's not in the builtins section of the docs.... or maybe that was some other language... bah.. too tired :-)
It is available as a list method:
http://www.python.org/dev/doc/devel/lib/typesseq-mutable.html
Here, all list methods are documented. Further, the way .sort()
works is explained, and it is exactly what you need.
You may want to write you own cmp() functions for sorting numeric, because
as far as I know, this does not exist yet, at least not in the standard
library (it may be a good exercise anyway).
yours,
Gerrit.
--
172. If her husband made her no gift, she shall be compensated for her
gift, and she shall receive a portion from the estate of her husband,
equal to that of one child. If her sons oppress her, to force her out of
the house, the judge shall examine into the matter, and if the sons are at
fault the woman shall not leave her husband's house. If the woman desire
to leave the house, she must leave to her sons the gift which her husband
gave her, but she may take the dowry of her father's house. Then she may
marry the man of her heart.
-- Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/