0

我需要打印出当前目录的 listdir,但按文件类型排序。像这样的东西:

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

这一切都在 python 中。在linux上有file命令。在python中怎么样?

4

2 回答 2

1

使用os模块,使用获取文件扩展名, os.path.splitext然后使用list.sort.

import os
files = os.listdir(path)
def func(x):
   return os.path.splitext(x)[::-1]
files.sort(key = func)

演示:

>>> 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']
于 2013-07-10T13:25:20.070 回答
0

知道了。正确的排序方法是:

files = os.listdir(folder)

files.sort(key=lambda f: os.path.splitext(f)[1])
于 2013-07-10T14:00:59.953 回答