Reputation: 201
I need to print out the listdir of current directory, but sorted by file type. Something like this:
ASCII text:
text
bzip2 compressed data, block size = 900k:
strace_4.5.20.orig.tar.bz2
gzip compressed data, extra field, from Unix:
openssh_5.8p1.orig.tar.gz
gzip compressed data, from Unix, last modified:
eglibc_2.11.2.orig.tar.gz
strace_4.5.20-2.debian.tar.gz
gzip compressed data, from Unix, max compression:
openssh_5.8p1-2.debian.tar.gz
PDF document, version 1.0:
attestazione.pdf
PDF document, version 1.2:
risPP.9dic03.pdf
risparz.7nov03.pdf
All this in python. On linux there's file
command. How about in python?
Upvotes: 0
Views: 2358
Reputation: 250961
Use the os
module, get the extension of a file using os.path.splitext
and then use list.sort
.
import os
files = os.listdir(path)
def func(x):
return os.path.splitext(x)[::-1]
files.sort(key = func)
Demo:
>>> lis = ['file1.zip', 'file2.zip', 'inotify.c', 'cmpsource.c', 'myfile.h']
>>> def func(x):
return os.path.splitext(x)[::-1]
>>> lis.sort(key = func)
>>> lis
['cmpsource.c', 'inotify.c', 'myfile.h', 'file1.zip', 'file2.zip']
Upvotes: 1
Reputation: 201
Got it. The right sorting method was:
files = os.listdir(folder)
files.sort(key=lambda f: os.path.splitext(f)[1])
Upvotes: 0