Question

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?

Was it helpful?

Solution

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']

OTHER TIPS

Got it. The right sorting method was:

files = os.listdir(folder)

files.sort(key=lambda f: os.path.splitext(f)[1])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top