Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get actual disk space of a file

Tags:

python

How do I get the actual filesize on disk in python? (the actual size it takes on the harddrive).

like image 291
Alex Avatar asked Nov 25 '10 08:11

Alex


People also ask

How do I check the disk space of a file?

1. Check File System Disk Space Usage. The “df” command displays the information of device name, total blocks, total disk space, used disk space, available disk space, and mount points on a file system.

How do I check disk space on a specific directory in Linux?

Linux command to check disk space using:df command – Shows the amount of disk space used and available on Linux file systems. du command – Display the amount of disk space used by the specified files and for each subdirectory.

How do I check the size of a Linux file system in GB?

That command is df -H. The -H switch is for human-readable format. The output of df -H will report how much space is used, available, percentage used, and the mount point of every disk attached to your system (Figure 1).


1 Answers

UNIX only:

import os
from collections import namedtuple

_ntuple_diskusage = namedtuple('usage', 'total used free')

def disk_usage(path):
    """Return disk usage statistics about the given path.

    Returned valus is a named tuple with attributes 'total', 'used' and
    'free', which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return _ntuple_diskusage(total, used, free)

Usage:

>>> disk_usage('/')
usage(total=21378641920, used=7650934784, free=12641718272)
>>>

Edit 1 - also for Windows: https://code.activestate.com/recipes/577972-disk-usage/?in=user-4178764

Edit 2 - this is also available in Python 3.3+: https://docs.python.org/3/library/shutil.html#shutil.disk_usage

like image 163
Giampaolo Rodolà Avatar answered Oct 22 '22 17:10

Giampaolo Rodolà