tags:

views:

29

answers:

2

I have a number of directories containing the files similar to the below example:

test
setup
adder
hello
_CONFIG
TEST2

The file(s) in these directories with the prefix _ represent configuration files of significance. The aim was to have these files appear first when I listed the directory i.e. I would like to be provided with:

_CONFIG
TEST2
adder
hello
setup
test

However, I am using

for element in sorted(os.listdir(path)):
    print(element)

and this provides a list where files starting in uppercase are listed above the _ prefixed files:

TEST2
_CONFIG
adder
hello
setup
test

Is there anyway around this without filtering each file by its first character and printing seperately as this would seem to be overkill.

Thank you

Tom

A: 
for element in sorted(os.listdir(path), key=lambda x:x.replace('_', ' ')):
    print(element)
Radomir Dopieralski
Hacky: relies on the list not containing any strings starting with " ". This is not guaranteed, at least not on Windows.
katrielalex
key=lambda x:x.replace('_', '\x00') should take care of that problem...
Steven
@katrielalex: Not at all, it just makes _ equivalent to space while sorting, which kinda makes sense to me.
Radomir Dopieralski
@radomir: So, which file comes first: " foo" or "_foo"? Answer: the wrong one, according to the original question.
Just Some Guy
@katrielalex: The answer is "whichever was first in the original list", as python's sort is stable and the `key` makes them equal for sorting.
Radomir Dopieralski
+2  A: 
sorted( ..., key = lambda s: ( not s.startswith( "_" ), s ) )
katrielalex
@katrielalex: That's great, thanks! Provides exactly what I need.
Thorsley