This is an approach using generators. Must be faster for a 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 need a list of files without size, you can use this:
sorted_files = sorted(all_files, key = os.path.getsize)
But if you need the files and paths in the 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) )
source share