Sort by File Size
This page was last reviewed on 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.
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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2023 (new).
© 2007-2024 Sam Allen.