Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Get File Size in Python (4 Ways)

  • 15 Jun, 2025
  • Com 0
How to Get File Size in Python

The file size is the number of bytes a file occupies in the file system. You can either retrieve it from metadata or calculate it.

Method 1 - Using os.path.getsize()

Here are four ways to find the file size in Python.

  1. Using os.path.getsize()
  2. Using os.stat()
  3. Using pathlib.Path.stat() (Modern Approach)
  4. Using the File object

Here is the “data.txt” file whose size we will find:

Screenshot of the data.txt file whose size we will find

Method 1: Using os.path.getsize()

The easiest way to determine the size of a file is to use the os.path.getsize() method. It returns the size in bytes and raises OSError if the file does not exist or is inaccessible.

import os

file_name = "data.txt"

file_size = os.path.getsize(file_name)

print(f'File Size in Bytes is {file_size}')
# Output: File Size in Bytes is 32

print(f'File Size in MegaBytes is {file_size / (1024 * 1024)}')
# Output: File Size in MegaBytes is 3.0517578125e-05

As shown in the above program, we calculated the file size in both bytes and megabytes. No additional metadata is returned, except for the file size.

If you want a secure approach that handles possible exceptions, you can use the approach below:

import os


def get_file_size(file_path):
    try:
        size = os.path.getsize(file_path)
        return size  # Size in bytes
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return None
    except PermissionError:
        print(f"Error: Permission denied for '{file_path}'.")
        return None


# Example usage
file_path = "data.txt"
size = get_file_size(file_path)

if size is not None:
    print(f"File size in bytes: {size} bytes")
    print(f'File Size in MegaBytes is {size / (1024 * 1024)}')

# Output:
# File size in bytes: 32 bytes
# File Size in MegaBytes is 3.0517578125e-05

Method 2: Using the os.stat()

Method 2 - Using the os.stat()

Another way is to use the os.stat() method. It returns several system-level details about a file, including its size.

import os


def get_file_size_stat(file_path, follow_symlinks=True):
    try:
        stat_info = os.stat(file_path, follow_symlinks=follow_symlinks)
        return stat_info.st_size  # Size in bytes
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return None
    except PermissionError:
        print(f"Error: Permission denied for '{file_path}'.")
        return None


# Example usage
file_path = "data.txt"
size = get_file_size_stat(file_path)
if size is not None:
    print(f"File size: {size} bytes")

# Output:
# File size: 32 bytes

Method 3: Using pathlib.Path.stat() (Modern Approach)

Method 3 - Using the Pathlib module

The pathlib module, available in Python 3.4 and later, provides an object-oriented approach to handling file system paths. It also provides a method to get the file size called the Path.stat() method.

from pathlib import Path


def get_file_size_pathlib(file_path):
    try:
        path = Path(file_path)
        return path.stat().st_size  # Size in bytes
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return None
    except PermissionError:
        print(f"Error: Permission denied for '{file_path}'.")
        return None


# Example usage
file_path = "data.txt"
size = get_file_size_pathlib(file_path)

if size is not None:
    print(f"File size: {size} bytes")

# Output:
# File size: 32 bytes

Method 4: Using File Object

This approach is a quick and efficient way to determine the size of a file without reading its contents into memory, making it suitable for large files.

def get_file_size_file_object(file_path):
    try:
        with open(file_path, 'rb') as f:
            f.seek(0, 2)  # Seek to end
            size = f.tell()  # Get position
            return size  # Size in bytes
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return None
    except PermissionError:
        print(f"Error: Permission denied for '{file_path}'.")
        return None


# Example usage
file_path = "data.txt"
size = get_file_size_file_object(file_path)

if size is not None:
    print(f"File size: {size} bytes")

# Output:
# File size: 32 bytes

We opened the “data.txt” file, moved the file pointer to the end, and then used the file.tell() method to get the pointer’s position, which equals the file size in bytes. Then, we printed the size both in bytes and converted it to megabytes.

That’s all!

Post Views: 26
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Delete File If It Exists in Python
How to List All Functions in Python Module

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend