Search code examples
pythonshutildisk-access

Bytes returned by "disk_usage" from the shutil library doesn't match the directory file size


I was reading the official documentation of shutil from the Python website, then I ran a disk_usage test, but it isn't returning what I was expecting, Inside that directory (folder) there's a single file of 669 kb.

This is the code:

import os
import shutil

os.chdir(r"D:\python\topics\shutil\disk_usage")

directory = "test_folder"

total, used, free = shutil.disk_usage(directory)

print(used)

Output:

177422868480 (which I suppose is the value in bytes)

Expected output:

669000 (since the file inside is 669 kb)

Why I'm not getting the expected output?

Thank you


Solution

  • shutil.disk_usage() returns statistics for the entire disk (filesystem, volume), not just for the specific directory you pass in.

    To compute disk space used by one directory and its subdirectories, see: Calculating a directory's size using Python?

    For a good introduction to some of the potential pitfalls, see: https://blogs.msdn.microsoft.com/oldnewthing/20041228-00/?p=36863