This is a approach using generators. Should be faster for large number of files…
This is the beginning of both examples:
import os, operator, sys
dirpath = os.path.abspath(sys.argv[0])
# make a generator for all file paths within dirpath
all_files = ( os.path.join(basedir, filename) for basedir, dirs, files in os.walk(dirpath) for filename in files )
If you just want a list of the files without the size, you can use this:
sorted_files = sorted(all_files, key = os.path.getsize)
But if you want files and paths in a list, you can use this:
# make a generator for tuples of file path and size: ('/Path/to/the.file', 1024)
files_and_sizes = ( (path, os.path.getsize(path)) for path in all_files )
sorted_files_with_size = sorted( files_and_sizes, key = operator.itemgetter(1) )
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…