1
import os
import string
os.chdir('C:\Python27')
x=os.listdir('C:\Python27')

y=[f for f in os.listdir(dirname)
    if os.path.isfile(os.path.join(dirname, f))]

for k in y:
    fileName, fileExtension = os.path.splitext(k)
    print fileName,fileExtension

And now, I want to sort the files by extension.

3 Answers 3

8

To sort by name, then by extension:

y.sort(key=os.path.splitext)

It produces the order:

a.2
a.3
b.1

To sort only by extension:

y.sort(key=lambda f: os.path.splitext(f)[1])

It produces the order:

b.1
a.2
a.3
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You very much, my friends!! I hope that you will have a splendid day;)You helped me a lot:D
2

Sort the list using a key function:

y.sort(key=lambda f: os.path.splitext(f))

Comments

0

without importing os module I think we can write like this. maybe there can be a shorter code but I could find this

from typing import List

def sort_by_ext(files: List[str]) -> List[str]:
    extensions = []
    for file in files:
        extensions.append(file.rsplit('.',1)[-1])
    indices = {k: i for i, k in enumerate(extensions)}
    return sorted(files, key=lambda s: indices[s.rsplit('.', 1)[1]], reverse = True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.