Python Sort by File SizeSort a list of files in a directory by their sizes. Use the os.listdir method.
Sort files, size. A directory contains files of many sizes. Which are the smallest and largest files? With the "os" module, we can list the files and get their sizes with getsize. We use a list of tuples.
This program, from a high level, creates a list of two-item tuples. Each tuple contains a file name and its size. It then sorts the list based on the size item of the tuples. It first imports the "os" module.
Listdir: The program uses the listdir method, part of the "os" module. The file names include no directories.Path
Join: It next uses the join method. This method combines the directory with the file name.
Getsize: It finally uses the getsize method. This returns the size. It adds a new tuple to the pairs list.
Finally: We call the sort method with an argument, a lambda expression that sorts based on a key. The key is the first element (the size) of each tuple.SortLambda
Python program that sorts files by size
# The folder containing files.
directory = "C:\\programs\\"
# Get all files.
list = os.listdir(directory)
# Loop and add files to list.
pairs = 
for file in list:
# Use join to get full file path.
location = os.path.join(directory, file)
# Get size and add to list of tuples.
size = os.path.getsize(location)
# Sort list of tuples by the first element, size.
pairs.sort(key=lambda s: s)
# Display pairs.
for pair in pairs:
In the resulting list, the files are sorted from smallest to largest. All the script files in my directory were small, between 184 bytes to 611 bytes. The list can be reversed with the reverse() method.
Summary. Sorting can be simple, as shown on many websites, or complex. Often elements must be sorted in an associative way. A list of tuples is ideal for this. A lambda expression can select the item to sort upon.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.