Skip to main content

How to get the size of a file in Python

How to get the size of a file in Python.

Here's a detailed step-by-step tutorial on how to get the size of a file in Python.

Step 1: Import the necessary modules

To get started, we need to import the os module, which provides a way to interact with the operating system. This module contains functions to work with files and directories.

import os

Step 2: Specify the file path

Next, we need to specify the path of the file for which we want to determine the size. You can either provide the absolute path (e.g., C:/path/to/file.txt) or the relative path (e.g., file.txt if it is in the same directory as your Python script).

file_path = 'path/to/your/file.txt'

Step 3: Check if the file exists

Before getting the size of the file, it's a good practice to check if the file actually exists. We can use the os.path.exists() function to do this.

if os.path.exists(file_path):
print("File exists.")
else:
print("File does not exist.")

Step 4: Get the file size

To get the size of the file, we can use the os.path.getsize() function. This function takes the file path as an argument and returns the size of the file in bytes.

file_size = os.path.getsize(file_path)

Step 5: Convert the file size to a human-readable format

By default, os.path.getsize() returns the file size in bytes. If you want to display the file size in a more human-friendly format (e.g., kilobytes or megabytes), you can create a helper function to convert it.

Here's an example function that converts the file size to a readable format:

def convert_size(size_bytes):
# 2**10 = 1024
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return f"{s} {size_name[i]}"

Now, you can use this function to convert the file size:

human_readable_size = convert_size(file_size)
print(f"File size: {human_readable_size}")

Complete example

Here's the complete example code that incorporates all the steps mentioned above:

import os
import math

def convert_size(size_bytes):
# 2**10 = 1024
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return f"{s} {size_name[i]}"

file_path = 'path/to/your/file.txt'

if os.path.exists(file_path):
print("File exists.")
file_size = os.path.getsize(file_path)
human_readable_size = convert_size(file_size)
print(f"File size: {human_readable_size}")
else:
print("File does not exist.")

That's it! You now have a detailed step-by-step tutorial on how to get the size of a file in Python.