Custom sort of directory contents
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 conf开发者_如何学Goiguration 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
sorted( ..., key = lambda s: ( not s.startswith( "_" ), s ) )
for element in sorted(os.listdir(path), key=lambda x:x.replace('_', ' ')):
print(element)
精彩评论