'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.
Solution 1:[1]
Sort the list using a key
function:
y.sort(key=lambda f: os.path.splitext(f))
Solution 2:[2]
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
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Martijn Pieters |
Solution 2 | jfs |
Solution 3 | Mylinear |