Python Program to Check the File Size

Updated on September 30, 2024
Check the File Size header image

Introduction

Checking the file size is a common operation in Python programming, especially when dealing with file management or data processing applications. By checking the size of a file, you can determine whether it's suitable for upload, processing, or storage, and you can make decisions based on its size.

In this article, you will learn how to utilize Python to check the size of a file. You will explore how to implement this using the built-in os module and how to handle exceptions to ensure your program is robust.

Checking File Size Using os.path.getsize()

Basic Example of Obtaining File Size

  1. Import the os module.

  2. Specify the path to the file whose size you want to check.

  3. Use os.path.getsize() to retrieve the file size.

    python
    import os
    
    file_path = 'example.txt'
    file_size = os.path.getsize(file_path)
    print("File Size in Bytes:", file_size)
    

    This code retrieves the size of example.txt in bytes and prints it. os.path.getsize() directly gives the size of the file located at the specified path.

Handling File Not Found Errors

  1. Use the try and except block to handle exceptions.

  2. Attempt to get the file size and catch any FileNotFoundError.

    python
    import os
    
    file_path = 'nonexistent_file.txt'
    try:
        file_size = os.path.getsize(file_path)
        print("File Size in Bytes:", file_size)
    except FileNotFoundError:
        print(f"File `{file_path}` not found.")
    

    In this example, if the file doesn't exist, it catches the FileNotFoundError and prints a custom message. Handling exceptions is crucial to prevent your program from crashing when errors occur during file operations.

Using Pathlib for Enhanced File Handling

  1. Import the pathlib module for object-oriented file system paths.

  2. Create a Path object and use its stat() method to get file details.

    python
    from pathlib import Path
    
    file_path = Path('example.txt')
    file_size = file_path.stat().st_size
    print("File Size in Bytes:", file_size)
    

    This block of code demonstrates how to use Pathlib, a modern file handling method in Python. It provides an object-oriented interface and is often easier to work with than the os module.

Conclusion

Checking the file size in Python is straightforward using the os module's os.path.getsize() method or the more modern Pathlib approach. Both methods provide efficient ways to retrieve file size, but Pathlib offers enhanced syntax and additional capabilities. By employing good exception handling practices, as shown in the provided examples, you ensure that your applications are robust and can handle unexpected situations gracefully. Utilize these techniques in your file-handling programs for effective and efficient results.