user2003611
user2003611

Reputation: 13

What is the function in Python that sort files by extension?

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.

Upvotes: 1

Views: 10354

Answers (3)

Mylinear
Mylinear

Reputation: 1

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)

Upvotes: 0

jfs
jfs

Reputation: 414405

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

Upvotes: 8

Martijn Pieters
Martijn Pieters

Reputation: 1122512

Sort the list using a key function:

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

Upvotes: 2

Related Questions