How To Compare File Size In Python

There are many instances when working with Python where you may want to compare the file sizes between two or more files. By determining the file size, you can perform various tasks such as organizing files, deleting large files, or finding duplicates. This tutorial will show you how to compare file sizes in Python using the built-in os module.

To demonstrate comparing file sizes in this tutorial, we will create two example text files, file1.txt and file2.txt.

Content of file1.txt:

Hello, this is some random text.

Content of file2.txt:

Hello, this is another text file with a bit more content to make it larger than the first 
file.

Step 1: Import the OS module

First, we need to import the os module in our Python script. This module provides a way to interact with the file system and retrieve information about given files.

Step 2: Get the file size using os.path.getsize()

We will use the os.path.getsize() function to get the size of each file in bytes. This function takes the file’s path as an argument and returns the file size.

Output:

File 1 Size: 747 bytes
File 2 Size: 1619 bytes
File 1 is smaller than File 2.

Step 3: Compare file size

Now that we have the file sizes, we can compare them using simple conditional statements to determine which file is larger, smaller, or if they are of equal size.

Output:

File 1 is smaller than File 2.

Full Code

Here’s the complete code for comparing file sizes in Python:

Output:

File 1 Size: 747 bytes
File 2 Size: 1619 bytes
File 1 is smaller than File 2.

Conclusion

Comparing file sizes in Python is simple and powerful using the os module’s getsize() function. This tutorial showed you how to fetch file sizes in bytes and how to compare them using conditional statements. This knowledge can be helpful when working with file manipulation, clean-up, and organization tasks in your Python projects.