python - 我想用 Python 列出一个目录,然后按大小对文件名进行排序

标签 python

下面获取文件,但是没有排序。

    for fn in os.listdir(path):

        if fn[0] == '.':
            continue

        try:
            p = os.path.join(path, fn)
        except:
            continue

        s = os.lstat(p)

        if stat.S_ISDIR(s.st_mode):
            l.append((fn, build_tree(p)))
        elif stat.S_ISREG(s.st_mode):
            l.append((fn, s.st_size))

最佳答案

一种方式

>>> import operator
>>> import os
>>> getall = [ [files, os.path.getsize(files)] for files in os.listdir(".") ]
>>> sorted(getall, key=operator.itemgetter(1))

关于python - 我想用 Python 列出一个目录,然后按大小对文件名进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5575706/

相关文章:

python - 错误 400 : invalid_request The out-of-band (OOB) flow has been blocked in order to keep users secure

python - 如何将下面显示的 excel 函数转换为 python pandas 代码?

python - 使用默认回退选项过滤列表值

Python - Pandas Dataframe 获取 n 行的平均值

Python csv.reader vs csv.dictreader 区别?

python - 弃用警告 : please use dns. resolver.Resolver.resolve()

python - 关于 Flask 中的 as_view 函数

python - 计算序列中的模式

python - Python 中具有接口(interface)和继承的多级抽象

python - Redisearch合计返回每组前5名