On Wed, 23 Nov 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. How
> to use ?
>
> dirs_files = os.listdir(os.getcwd())
> print dirs_files
> dirs_files.sort()
> print dirs_files
Hi lmac,
I can't duplicate this. Can you show us the output that you see? Do any
of the list elements permute at all?
Here's what happens on my own system:
######
>>> files = os.listdir("/etc/init.d")
>>> files
['README', 'acctadm', 'ldap.client', 'mkdtab', 'nscd', 'ufs_quota',
'devlinks', 'drvconfig', 'acct', 'dhcp', 'nfs.server', 'pcmcia', 'slpd',
'sendmail', 'Wnn6', 'sysetup', 'cachefs.daemon', 'PRESERVE', 'deallocate',
'autoinstall', 'dodatadm.udaplt', 'uucp', 'lu', 'ncakmod', 'appserv',
'audit', 'samba', 'apache', 'imq', 'volmgt', 'init.wbem', 'boot.server',
'llc2', 'dtlogin', 'webconsole', 'atsv', 'init.dmi', 'init.snmpdx',
'mipagent', 'ncalogd', 'IIim', 'pppd', 'loc.ja.cssd', 'init.sma',
'installupdates', 'cswopenldap', 'cswmysql', 'samba.old', 'mysql.server',
'patchserver', 'mysql.server~', 'init.wbem.119314-03']
>>> files.sort()
>>> files
['IIim', 'PRESERVE', 'README', 'Wnn6', 'acct', 'acctadm', 'apache',
'appserv', 'atsv', 'audit', 'autoinstall', 'boot.server',
'cachefs.daemon', 'cswmysql', 'cswopenldap', 'deallocate', 'devlinks',
'dhcp', 'dodatadm.udaplt', 'drvconfig', 'dtlogin', 'imq', 'init.dmi',
'init.sma', 'init.snmpdx', 'init.wbem', 'init.wbem.119314-03',
'installupdates', 'ldap.client', 'llc2', 'loc.ja.cssd', 'lu', 'mipagent',
'mkdtab', 'mysql.server', 'mysql.server~', 'ncakmod', 'ncalogd',
'nfs.server', 'nscd', 'patchserver', 'pcmcia', 'pppd', 'samba',
'samba.old', 'sendmail', 'slpd', 'sysetup', 'ufs_quota', 'uucp', 'volmgt',
'webconsole']
######
Everything appears to sort fine.
The files that start with uppercase come first because of the way those
strings compare to lowercase strings. If we want a case-insensitive sort,
we can do something like this:
######
>>> def case_insensitive_cmp(a, b):
... return cmp(a.upper(), b.upper())
...
>>> files.sort(case_insensitive_cmp)
>>> files
['acct', 'acctadm', 'apache', 'appserv', 'atsv', 'audit', 'autoinstall',
'boot.server', 'cachefs.daemon', 'cswmysql', 'cswopenldap', 'deallocate',
'devlinks', 'dhcp', 'dodatadm.udaplt', 'drvconfig', 'dtlogin', 'IIim',
'imq', 'init.dmi', 'init.sma', 'init.snmpdx', 'init.wbem',
'init.wbem.119314-03', 'installupdates', 'ldap.client', 'llc2',
'loc.ja.cssd', 'lu', 'mipagent', 'mkdtab', 'mysql.server',
'mysql.server~', 'ncakmod', 'ncalogd', 'nfs.server', 'nscd',
'patchserver', 'pcmcia', 'pppd', 'PRESERVE', 'README', 'samba',
'samba.old', 'sendmail', 'slpd', 'sysetup', 'ufs_quota', 'uucp', 'volmgt',
'webconsole', 'Wnn6']
######
Hope this helps!
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor