Home
Python
Sort by File Size
Updated Nov 17, 2023
Dot Net Perls
Sort files, size. Which are the smallest and largest files in a directory? With the "os" module, we can list the files and get their sizes with getsize.
In Python, we can use a list of tuples to store the file paths along with their sizes in bytes. Then a separate sort() call can perform the required reordering.
Tuple
This program creates a list of 2-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.
Step 1 The program uses the listdir method, part of the "os" module. The file names include no directories.
Path
Step 2 We loop over the files in the specified directory. In this loop, we add files to a list of tuples.
Step 3 The program uses the join method. This method combines the directory with the file name.
Step 4 It finally uses the getsize method. This returns the size. It adds a new tuple to the pairs list.
Step 5 We call sort() with a lambda that sorts based on a key. The key is the first element (the size) of each tuple.
sort
lambda
import os # Step 1: get all files. directory = "programs/" list = os.listdir(directory) # Step 2: loop and add files to list. pairs = [] for file in list: # Step 3: Use join to get full file path. location = os.path.join(directory, file) # Step 4: get size and add to list of tuples. size = os.path.getsize(location) pairs.append((size, file)) # Step 5: sort list of tuples by the first element, size. pairs.sort(key=lambda s: s[0]) for pair in pairs: print(pair)
(184, 'file.pl') (235, 'file.php') (369, 'file.rb') (611, 'file.py')
Results. In the resulting list, the files are sorted from smallest to largest. The list can be reversed with the reverse() method.
And This code could be used to determine the largest files in a directory, which might need to be deleted first.
Summary. Sorting can be simple, but 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 17, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen