[Tutor] sort list alphabetically

bob bgailer at alum.rpi.edu
Thu Nov 24 00:14:47 CET 2005


At 09:55 AM 11/23/2005, lmac wrote:
>i have a list with the dirs/files from the current path. When i use
>sort() to sort the list alphabetically the list is still unsorted.

When you say "unsorted" - are the list members in the same order as 
before the sort?

>dirs_files = os.listdir(os.getcwd())
>print dirs_files
>dirs_files.sort()
>print dirs_files

Works for me. On my computer:
 >>> dirs_files = os.listdir(os.getcwd())
 >>> for x in dirs_files[:10]:x
"'01GRTfiles"
'archive'
'backup'
'CU'
'data'
'documents'
'error_tbls_in'
'error_tbls_out'
'forms'
'GRTFiles'
 >>> dirs_files.sort()
 >>> for x in dirs_files[:10]:x
"'01GRTfiles"
'CU'
'DIST_TEST.DBF'
'DUP_ATTR2.BAK'
'DUP_ATTR2.DBF'
'GRTFiles'
'GRT_CS_SA.DBF'
'GRT_ITEM_XREF.DBF'
'IMP_MC_CR.BAK'
'IMP_MC_CR.DBF'

You may notice that sort is case sensitive. The names beginning with 
lower case letters follow all the names beginning with upper case 
letters. If you want case insensitivity,
dirs_files = [x.lower() for x in dirs_files] before sorting. 



More information about the Tutor mailing list