Best Way To Check File Size in Python

Sharing is Caring

When working with files, it’s important to have a way to check file size in Python, as it can affect their performance and storage requirements. Fortunately, Python provides a straightforward and efficient way to check the file size using built-in modules. In this blog post, we will explore how to check file size in Python using the os module and the os.path.getsize() method. We’ll also look at how to display file size in a human-readable format and convert it to different units. Additionally, we’ll demonstrate how to check the size of multiple files at once. By the end of this blog post, you’ll have a clear understanding of how to check file size in Python and be able to apply it to your own projects.

Check File Size in Python

How to Check File Size in Python by using os.path.getsize()?

When it comes to checking file size in Python, one of the easiest and most straightforward ways is to use the os module’s os.path.getsize() method. The os module is a built-in module in Python that provides a way to interact with the operating system. With the os.path.getsize() method, you can retrieve the size of a file in bytes. This method takes the path of the file as an argument and returns the size of the file in bytes. If you encounter an “ImportError” when trying to import the os module, it might be because the module is not installed on your system.

To use os.path.getsize() method, you first need to import the os module into your Python script. Here’s an example:

import os

Next, you can use the os.path.getsize() method to retrieve the size of a file. Here’s an example:

file_path = 'path/to/your/file.txt'
file_size = os.path.getsize(file_path)
print(f"The size of {file_path} is {file_size} bytes.")

In the above example, we first define the path to the file we want to check the size of. We then pass this path to the os.path.getsize() method to retrieve the size of the file. Finally, we print out the file size in bytes.

It’s important to note that the os.path.getsize() method returns the size of the file in bytes. If you want to display the file size in a more human-readable format, such as kilobytes (KB), megabytes (MB), or gigabytes (GB), you’ll need to convert the file size to the appropriate unit. We’ll cover this in more detail in the next section.

Human-Readable File Size with sizeof_fmt()

Luckily, Python provides a simple way to convert file sizes from bytes to a more human-readable format using the sizeof_fmt() function.

The sizeof_fmt() function is not a built-in function in Python, so you’ll need to define it in your code before you can use it. Here’s the code for the function:

def sizeof_fmt(num, suffix='B'):
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return f"{num:3.1f} {unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f} Y{suffix}"

The function takes two arguments: num, which is the size of the file in bytes, and suffix, which is the unit of the file size. By default, the suffix is set to ‘B’ for bytes. The function then uses a for loop to iterate through a list of units, starting with an empty string and ending with ‘Z’. The function checks if the absolute value of the file size is less than 1024.0, which is the maximum size for a given unit, and if it is, it returns the size with the appropriate unit and suffix. If the file size is larger than 1024.0, the function divides it by 1024.0 and moves to the next unit. This process continues until the file size is less than 1024.0, or until it reaches the largest possible unit (‘Z’).

Also Read: Fix ‘python3’ is not recognized as an internal or external command, operable program or batch file [Easily]

Now that you have the sizeof_fmt() function defined, you can use it with the os module’s os.path.getsize() method to retrieve the size of a file in a human-readable format. Here’s an example:

import os

def sizeof_fmt(num, suffix='B'):
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return f"{num:3.1f} {unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f} Y{suffix}"

file_path = 'path/to/your/file.txt'
file_size = os.path.getsize(file_path)

print(f"The size of {file_path} is {sizeof_fmt(file_size)}.")

In the above example, we first import the os module and define the sizeof_fmt() function. We then define the path to the file we want to check the size of and use os.path.getsize() to retrieve the size of the file in bytes. Finally, we use sizeof_fmt() to convert the file size to a human-readable format and print it out.

Check the File Size of Multiple Files

If you need to check the sizes of multiple files in Python, you can use a loop to iterate over a list of file paths and use the os.path.getsize() method to retrieve the size of each file. Here’s an example:

import os

def sizeof_fmt(num, suffix='B'):
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return f"{num:3.1f} {unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f} Y{suffix}"

file_paths = ['path/to/your/file1.txt', 'path/to/your/file2.txt', 'path/to/your/file3.txt']

for file_path in file_paths:
    file_size = os.path.getsize(file_path)
    print(f"The size of {file_path} is {sizeof_fmt(file_size)}.")

In this example, we define a list of file paths and use a for loop to iterate over each path. Within the loop, we use os.path.getsize() to retrieve the size of each file and then use the sizeof_fmt() function to convert the size to a human-readable format. Finally, we print out the size of each file.

If you have a large number of files to check, you can use the glob module to create a list of file paths that match a specific pattern. For example, if you want to check the sizes of all files with the .txt extension in a directory, you can use the following code:

import os
import glob

def sizeof_fmt(num, suffix='B'):
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return f"{num:3.1f} {unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f} Y{suffix}"

file_paths = glob.glob('path/to/your/directory/*.txt')

for file_path in file_paths:
    file_size = os.path.getsize(file_path)
    print(f"The size of {file_path} is {sizeof_fmt(file_size)}.")

In this example, we use the glob.glob() method to create a list of all file paths that match the pattern ‘path/to/your/directory/*.txt’. We then use a for loop to iterate over each path, retrieve the size of the file using os.path.getsize(), and print out the size of each file in a human-readable format using the sizeof_fmt() function.

Conclusion

In conclusion, checking file size in Python is a simple and essential task for any programmer. With the built-in os module, and the sizeof_fmt() function, it’s easy to retrieve and display the file size in a human-readable format.

FAQs

What is the maximum file size that can be checked using os.path.getsize()?

The maximum file size that can be checked using os.path.getsize() depends on the operating system and file system. In general, the maximum file size is limited by the number of bits used to represent the file size, which can vary depending on the system.

How can I check the file size in bytes instead of a human-readable format?

By default, os.path.getsize() returns the file size in bytes. If you don’t want to convert the size to a human-readable format, you can simply use the value returned by the method.

Can I check the size of a remote file using Python?

Yes, you can check the size of a remote file using Python, but you’ll need to use a library or module that supports remote file access, such as the paramiko module or the ftplib module.

Leave a Comment