How to Get File and Directory (Folder) Size with Python?


Sometimes, you need to know how large a file or directory is. Maybe you’re trying to clean up your storage space, or you want to make sure a file you’re downloading is the right size. In this blog post, we’ll show you how to get the size of a file or directory using Python.

Use the os.path.getsize() function to get the size of a file in Python

This function accepts a single argument, which is the path to the file or directory whose size you want to determine.

if you want to know the current folder, you can see this post.

For example: get file size python using os module and os.path.getsize function.

import os size = os.path.getsize("/Users/david/DLK_MOBIL_BODY.sql") print(size) # 191552 byte
Code language: Python (python)

Note: As you may already know, os.path.get_size() function only returns the correct size of proper files and not folders.

Get File Size in KB, MB, or GB

Use the following example to convert the file size in KB, MB, or GB.

import os.path # calculate file size in KB, MB, GB def convert_bytes(size): """ Convert bytes to KB, or MB or GB""" for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if size < 1024.0: return "%3.1f %s" % (size, x) size /= 1024.0 file_size = os.path.getsize("/Users/david/DLK_MOBIL_BODY.sql") fz = convert_bytes(file_size) print("File size is ", fz)
Code language: Python (python)

Using os.stat().st_size

In this method, we will use the os module’s stat() function. It gives back a lot of information about a path.

import os size = os.stat("/Users/david/DLK_MOBIL_BODY.sql").st_size print(size) # 191552
Code language: Python (python)

To convert File Size in KB, MB, or GB, using humanize package. First, install the humanize package, by running the following command in your shell:

pip install humanize

Then you can use the naturalsize() function, which turns a value in bytes into a file size that can be read, such as KB, MB, GB, or TB.

import os from humanize import naturalsize size = os.stat('/Users/david/DLK_MOBIL_BODY.sql').st_size print(size) # 191552 print(naturalsize(size)) # 191.6 kB
Code language: Python (python)

Using Pathlib Module to Get File Size

Starting with Python 3.4, we can use the pathlib module, which wraps most OS functions.

Import pathlib module: Pathlib module has classes and methods to handle filesystem paths and get information about files for different operating systems.

Next, using the pathlib.

Path(‘path’).stat().st_size will give you the size of the file in bytes.

import pathlib from humanize import naturalsize path = pathlib.Path('/Users/david/DLK_MOBIL_BODY.sql') f_size = path.stat().st_size print('File size in bytes', f_size) # display file size in KB or MB print('file size is', naturalsize(size))
Code language: Python (python)

Get Directory (Folder) Size using Python

How to make a simple function in Python to figure out how big a folder is as a whole?

The below core function calculates the total size of a folder given its relative or absolute path:

import os def get_folder_size(path_folder): """Returns the folder size in bytes.""" total = 0 try: # print("[+] Getting the size of", path_folder) for entry in os.scandir(path_folder): if entry.is_file(): # if it's a file, use stat() function total += entry.stat().st_size elif entry.is_dir(): # if it's a folder, recursively call this function try: total += get_folder_size(entry.path) except FileNotFoundError: pass except NotADirectoryError: # if 'folder' isn't a folder, get the file size then return os.path.getsize(folder) except PermissionError: # if for whatever reason we can't open the folder, return 0 return 0 return total
Code language: Python (python)

The os.scandir() function returns an iterator of directory entries (files or directories) in the directory given.

The above code returns the size in bytes, which is unreadable for large folders. Let’s construct a function to scale bytes to Kilo, Mega, Giga, etc.

def get_size_format(x, factor=1024, mysuffix="B"): """ Scale bytes to its proper byte format e.g: 1293656 => '1.30MB' 1253656676 => '1.17GB' """ for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: if x < factor: return f"{x:.2f}{unit}{mysuffix}" x /= factor return f"{x:.2f}Y{mysuffix}"
Code language: Python (python)

Okay, I’ll test this on my D drive, which I know is big:

get_size_format(get_directory_size("D:\\"))
Code language: JavaScript (javascript)

This took about a minute, and the following result came back:

'150.91GB'
Code language: JavaScript (javascript)

Get directory (folder) size: use os.scandir()

To calculate the total size of the files contained in a directory (folder), use os.scandir().

def get_folder_size(path='.'): total = 0 with os.scandir(path) as it: for item in it: if item.is_file(): total += item.stat().st_size elif item.is_dir(): total += get_dir_size(item.path) return total print(get_folder_size('data/images')) # 66130856
Code language: Python (python)

Get directory (folder) size: use os.listdir()

def get_folder_size_old(path='.'): total = 0 for p in os.listdir(path): full_path = os.path.join(path, p) if os.path.isfile(full_path): total += os.path.getsize(full_path) elif os.path.isdir(full_path): total += get_dir_size_old(full_path) return total print(get_folder_size_old('data/images')) # 56130856
Code language: Python (python)

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts