Getting File Size in Python

In this tutorial, we will cover how to get the size of a file in Python. There are several ways to achieve this, and we will explore each method with examples.

Introduction

When working with files in Python, it’s often necessary to know the size of the file. This can be useful for various purposes such as checking if a file exists, calculating storage space, or optimizing file uploads/downloads.

Using os.path.getsize()

The most straightforward way to get the size of a file is by using the os.path.getsize() function from the os module. Here’s an example:

import os

file_path = "/path/to/file.txt"
try:
    file_size = os.path.getsize(file_path)
    print(f"The size of {file_path} is {file_size} bytes")
except FileNotFoundError:
    print(f"File {file_path} not found")

This function returns the size of the file in bytes.

Using os.stat()

Another way to get the size of a file is by using the os.stat() function, which returns an object containing information about the file. We can access the file size through the st_size attribute:

import os

file_path = "/path/to/file.txt"
try:
    file_info = os.stat(file_path)
    file_size = file_info.st_size
    print(f"The size of {file_path} is {file_size} bytes")
except FileNotFoundError:
    print(f"File {file_path} not found")

Using pathlib

For Python 3.4 and later, you can use the pathlib module to get the file size. This provides a more object-oriented way of interacting with files:

from pathlib import Path

file_path = Path("/path/to/file.txt")
try:
    file_size = file_path.stat().st_size
    print(f"The size of {file_path} is {file_size} bytes")
except FileNotFoundError:
    print(f"File {file_path} not found")

Converting File Size to Human-Readable Format

To make the file size more readable, you can convert it from bytes to a human-friendly format like kilobytes (KB), megabytes (MB), gigabytes (GB), etc. Here’s an example function that does this:

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

# Example usage:
file_size = os.path.getsize("/path/to/file.txt")
print(convert_bytes(file_size))

This function takes the file size in bytes as input and returns a string representing the size in a human-readable format.

Handling File-Like Objects

If you’re working with file-like objects (e.g., StringIO), you can use the seek() method to get the file size:

import os

# Assume 'f' is a file-like object
old_file_position = f.tell()
file_size = f.seek(0, os.SEEK_END)
f.seek(old_file_position)
print(f"The size of the file-like object is {file_size} bytes")

Note that this approach assumes you have read permission for the file-like object.

In conclusion, getting the size of a file in Python can be achieved through various methods, including os.path.getsize(), os.stat(), and pathlib. You can also convert the file size to a human-readable format using a custom function.

Leave a Reply

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