[Tutor] Sorting a directory

Jonas Melian jonasmg at softhome.net
Tue May 24 17:02:17 CEST 2005


Kent Johnson wrote:
>>and i would sort this files by the 2 last letters, so:
> 
> The sort() method of a mutable sequence is very powerful. Docs for it are here:
> http://docs.python.org/lib/typesseq-mutable.html
> 
> The key= parameter of sort() allows you to provide a function which, given a member of the sequence 
> being sorted, returns the sort key for that item. In your case you can define a simple helper 
> function that returns the last two characters of a string:
> 
> def lastTwoChars(s):
>    return s[-2:]
> 
> then sort like this:
> 
> dir_locales = "/usr/share/i18n/locales/"
> 
> files = glob.glob(os.path.join(dir_locales, "*_[A-Z][A-Z]"))
> files.sort(key=lastTwoChars)	# Note: NOT key=lastTwoChars()
> 
> for line in fileinput.input(files):
>    ...
> 

Thanks for this information.

I get:
::
files.sort(key=lastTwoChars)
TypeError: sort() takes no keyword arguments
::

Could it be by the Python version? I have Python 2.3.5


More information about the Tutor mailing list