Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

How to get file size in Python

To check the file size in Python, you can use the os.path.getsize() function from the os module. This function returns the size of the specified file in bytes.

Here's an example of how to check the file size using the os.path.getsize() function:

import os

file_path = "file.txt"

# Check if the file exists
if os.path.exists(file_path):
    file_size = os.path.getsize(file_path)
    print(f"The size of '{file_path}' is {file_size} bytes.")
else:
    print(f"The file '{file_path}' does not exist.")

In this example, we first import the os module. We then use the os.path.exists() function to check if the file exists. If the file exists, we use the os.path.getsize() function to get the file size in bytes and print the result.

If you want to display the file size in a more human-readable format, you can write a helper function to convert bytes to an appropriate unit like KB, MB, GB, etc.:

def convert_bytes(num):
    for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return f"{num:.1f} {unit}"
        num /= 1024.0

file_size_bytes = os.path.getsize(file_path)
file_size_readable = convert_bytes(file_size_bytes)
print(f"The size of '{file_path}' is {file_size_readable}.")

In this example, we define a convert_bytes() function that takes the file size in bytes and converts it to a more readable format by iterating through different units until an appropriate unit is found. The function returns a formatted string with the file size and unit.

  1. Check file size in Python:

    import os
    
    def check_file_size(file_path):
        size = os.path.getsize(file_path)
        print(f"File size of {file_path}: {size} bytes")
    
    # Example usage
    check_file_size("example.txt")
    
  2. Retrieve file size using os module in Python:

    import os
    
    file_path = "example.txt"
    size = os.path.getsize(file_path)
    print(f"File size of {file_path}: {size} bytes")
    
  3. Get file size in bytes with os.path.getsize():

    import os
    
    file_path = "example.txt"
    size = os.path.getsize(file_path)
    print(f"File size of {file_path}: {size} bytes")
    
  4. Python os.stat() file size:

    import os
    
    file_path = "example.txt"
    size = os.stat(file_path).st_size
    print(f"File size of {file_path}: {size} bytes")
    
  5. Check file size in kilobytes in Python:

    import os
    
    def check_file_size_kb(file_path):
        size_bytes = os.path.getsize(file_path)
        size_kb = size_bytes / 1024
        print(f"File size of {file_path}: {size_kb:.2f} KB")
    
    # Example usage
    check_file_size_kb("example.txt")
    
  6. Python pathlib.Path file size:

    from pathlib import Path
    
    file_path = Path("example.txt")
    size = file_path.stat().st_size
    print(f"File size of {file_path}: {size} bytes")
    
  7. Calculate file size in megabytes with Python:

    import os
    
    def file_size_mb(file_path):
        size_bytes = os.path.getsize(file_path)
        size_mb = size_bytes / (1024 ** 2)
        print(f"File size of {file_path}: {size_mb:.2f} MB")
    
    # Example usage
    file_size_mb("example.txt")
    
  8. Get file size in gigabytes using Python:

    import os
    
    def file_size_gb(file_path):
        size_bytes = os.path.getsize(file_path)
        size_gb = size_bytes / (1024 ** 3)
        print(f"File size of {file_path}: {size_gb:.2f} GB")
    
    # Example usage
    file_size_gb("example.txt")
    
  9. Retrieve size of a directory in Python:

    import os
    
    def get_directory_size(directory_path):
        size = sum(os.path.getsize(os.path.join(directory_path, file)) for file in os.listdir(directory_path))
        print(f"Size of {directory_path}: {size} bytes")
    
    # Example usage
    get_directory_size("/path/to/directory")
    
  10. Check if a file is empty in Python:

    def is_file_empty(file_path):
        return os.path.getsize(file_path) == 0
    
    # Example usage
    if is_file_empty("example.txt"):
        print("File is empty")
    else:
        print("File is not empty")
    
  11. Get human-readable file size in Python:

    import os
    from hurry.filesize import size
    
    file_path = "example.txt"
    size_readable = size(os.path.getsize(file_path))
    print(f"File size of {file_path}: {size_readable}")
    
  12. Check file size and handle exceptions in Python:

    import os
    
    def check_file_size_safe(file_path):
        try:
            size = os.path.getsize(file_path)
            print(f"File size of {file_path}: {size} bytes")
        except FileNotFoundError:
            print(f"File not found: {file_path}")
        except Exception as e:
            print(f"An error occurred: {e}")
    
    # Example usage
    check_file_size_safe("example.txt")
    
  13. Calculate total size of files in a directory in Python:

    import os
    
    def total_directory_size(directory_path):
        total_size = sum(os.path.getsize(os.path.join(directory_path, file)) for file in os.listdir(directory_path))
        print(f"Total size of files in {directory_path}: {total_size} bytes")
    
    # Example usage
    total_directory_size("/path/to/directory")