Help sorting a list by file extension

Peter A. Schott paschott at no.yahoo.spamm.com
Fri Aug 12 18:15:40 CEST 2005


OK - I actually got something working last night with a list that is then
converted into a dictionary (dealing with small sets of data - < 200 files per
run).  However, I like the sorted list option - I didn't realize that was even
an option within the definition and wasn't quite sure how to get there.  I
realized I could use os.path.splitext and cast that to an int, but was having
trouble with the sort.

My files only have a single "." in them so this will work well for me.

	(from Tom's code)
[name for dec,name in
sorted((int(os.path.splitext(nm)[1][1:]),nm) for nm in namelist)]

I'll give that a try - it would eliminate the dictionary part of my code and be
a little more efficient.

Thanks to all for the quick responses.

-Pete

Peter A. Schott <paschott at no.yahoo.spamm.com> wrote:

> Trying to operate on a list of files similar to this:
> 
> test.1
> test.2
> test.3
> test.4
> test.10
> test.15
> test.20
> 
> etc.
> 
> I want to sort them in numeric order instead of string order.  I'm starting with
> this code:
> 
> import os
> 
> for filename in [filename for filename in os.listdir(os.getcwd())]:
> 	print filename
> 	#Write to file, but with filenames sorted by extension
> 
> 
> Desired result is a file containing something like:
> C:\MyFolder\test.1,test.001
> C:\MyFolder\test.2,test.002
> C:\MyFolder\test.3,test.003
> C:\MyFolder\test.4,test.004
> C:\MyFolder\test.10,test.010
> C:\MyFolder\test.15,test.015
> C:\MyFolder\test.20,test.020
> 
> I need to order by that extension for the file output.
> 
> I know I've got to be missing something pretty simple, but am not sure what.
> Does anyone have any ideas on what I'm missing?
> 
> Thanks.
> 
> -Pete Schott



More information about the Python-list mailing list