[Tutor] Sorting a directory
Kent Johnson
kent37 at tds.net
Tue May 24 16:18:55 CEST 2005
Jonas Melian wrote:
> Hi all,
>
> I have to working with the files lines in this directory:
>
> :::
> dir_locales = "/usr/share/i18n/locales/"
>
> for line in fileinput.input(glob.glob(os.path.join\
> (dir_locales, "*_[A-Z][A-Z]"))):
> ...
>
> :::
>
> The problem is that the directory otuput is:
> aa_DJ
> aa_ER
> aa_ET
> af_ZA
> ...
>
> and i would sort this files by the 2 last letters, so:
> aa_DJ
> so_DJ
> aa_ER
> byn_ER
> gez_ER
> ti_ER
> tig_ER
> ...
>
> I have not foun a lot of info about sort
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):
...
Kent
More information about the Tutor
mailing list