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.
1 |
import os |
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.
1 2 3 4 5 |
file1_size = os.path.getsize('file1.txt') file2_size = os.path.getsize('file2.txt') print(f"File 1 Size: {file1_size} bytes") print(f"File 2 Size: {file2_size} bytes") |
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.
1 2 3 4 5 6 |
if file1_size > file2_size: print("File 1 is larger than File 2.") elif file1_size < file2_size: print("File 1 is smaller than File 2.") else: print("File 1 and File 2 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import os file1_size = os.path.getsize('file1.txt') file2_size = os.path.getsize('file2.txt') print(f"File 1 Size: {file1_size} bytes") print(f"File 2 Size: {file2_size} bytes") if file1_size > file2_size: print("File 1 is larger than File 2.") elif file1_size < file2_size: print("File 1 is smaller than File 2.") else: print("File 1 and File 2 are of equal size.") |
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.