How to sort a list of file paths
john.eriksson at logica.com
Tue Dec 2 09:36:02 CET 2008
This weekend I had some problems to get a list containing file paths to be sorted in a way that I could use.
I also found a thread in this mailing list ( http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and realized that others might be interested in a solution.
So... here is my five cents regarding file path sorting:
You have a list containing some file names:
>>> file_list = ["File2.txt","File1.txt","File10.txt"]
If you sort this list in the conventional way you end up with a result like:
>>> print file_list
Sort the list by splitting alphas and digits in to groups and compare them separately.
aa = re.findall(r'\d |\D ', a)
bb = re.findall(r'\d |\D ', b)
for i in range(min(len(aa),len(bb))):
if aa[i].isdigit() and bb[i].isdigit():
c = cmp(int(aa[i]),int(bb[i]))
c = cmp(aa[i],bb[i])
file_list = ["File2.txt","File1.txt","File10.txt"]
If the formatting in this mail is messed up you can find the example at http://arainyday.se/notebook/true_alphanum_cmp.php
All comments and improvements are welcome!
Logica - Releasing your potential
904 20 UMEÅ
T: +46 (0) 90 15 91 38
M: +46 (0) 70 366 16 77
E: john.eriksson at logica.com<mailto:john.eriksson at logica.com>
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list