Skip to main content

How to sort files by size in Python

How to sort files by size in Python.

Here's a step-by-step tutorial on how to sort files by size in Python:

Step 1: Import the necessary modules

First, you need to import the os and operator modules. The os module provides a way to interact with the operating system, and the operator module provides convenient functions for sorting.

import os
import operator

Step 2: Define a function to get file sizes

Next, you can define a function that takes a directory path as input and returns a dictionary mapping file names to their sizes. This function will use the os.path.getsize() method to get the size of each file.

def get_file_sizes(directory):
file_sizes = {}
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath):
file_sizes[filename] = os.path.getsize(filepath)
return file_sizes

Step 3: Get file sizes and sort them

Now, you can call the get_file_sizes() function to get the file sizes for a specific directory. After that, you can use the sorted() function to sort the dictionary by its values (file sizes). You can pass the items() method of the dictionary to the sorted() function along with the key parameter set to operator.itemgetter(1) to sort by the values.

directory_path = '/path/to/directory'
file_sizes = get_file_sizes(directory_path)
sorted_files = sorted(file_sizes.items(), key=operator.itemgetter(1))

The sorted_files variable will now contain a list of tuples, where each tuple represents a file name and its corresponding size. The list is sorted in ascending order based on the file sizes.

Step 4: Print the sorted file sizes

To print the sorted file sizes, you can iterate over the sorted_files list and print each file name and its size.

for file_name, file_size in sorted_files:
print(f'{file_name}: {file_size} bytes')

You can modify the print statement as per your requirements, such as formatting the file size in a more human-readable format (e.g., kilobytes or megabytes).

That's it! You've successfully sorted files by size in Python.