从目录参数获取文件,按大小排序

从目录参数获取文件,按大小排序,第1张

从目录参数获取文件,按大小排序

希望此功能可以对您有所帮助(我正在使用Python 2.7):

import osdef get_files_by_file_size(dirname, reverse=False):    """ Return list of file paths in directory 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 xrange(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)    # Re-populate list with just filenames    for i in xrange(len(filepaths)):        filepaths[i] = filepaths[i][0]    return filepaths


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5663783.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存