新Unix用户的简单Python列表

时间:2017-04-12 03:43:51

标签: python unix

这可能看起来很愚蠢,但是我有一段时间试图编写一个Python 2.6函数,该函数采用目录路径并打印所有文件的大小(以字节为单位),忽略子目录。我还想按大小反向排序,如下所示:

fileA:50000

fileB:40000

fileC:30000

档案 - 总计:120000

任何人都可以伸出援手吗?

2 个答案:

答案 0 :(得分:1)

略微修改this answer我们可以得到一个包含(filename,filesize)的两元组列表。

import os

def get_files_by_file_size(dirname, reverse=False):
    """ Return list of two-tuples with file paths and file sizes 
        sorted by file size """

    # Get list of files
    filepaths = []
    for basename in os.listdir(dirname):
        filename = os.path.join(dirname, basename)
        if os.path.isfile(filename):
            filepaths.append(filename)

    # Re-populate list with filename, size tuples
    for i in range(len(filepaths)):
        filepaths[i] = (filepaths[i], os.path.getsize(filepaths[i]))

    # Sort list by file size
    # If reverse=True sort from largest to smallest
    # If reverse=False sort from smallest to largest
    filepaths.sort(key=lambda filename: filename[1], reverse=reverse)

    return filepaths

你会这样称呼:

dirname = os.getcwd()
get_files_by_file_size(dirname,reverse=True)

答案 1 :(得分:0)

import os

all_files = list()

dir_path = "." # replace with actual dir path

for file in os.listdir(dir_path):
    path = os.path.join(dir_path, file)
    if os.path.isfile(path):
        all_files.append(tuple([file, os.path.getsize(path)]))

all_files.sort(key = lambda elm: elm[1])

for item in all_files:
    print(item)