-1

How can I find the size on disk of a file container in Python? Please consider that I can't calculate the size on disk by using cluster size because the container may have empty space (see the picture)

size : 32,212,254,720 bytes

size on disk : 28,232,646,656 bytes

My operating system is Windows and using Python 3.8

view the image

Maria K
  • 1,491
  • 1
  • 3
  • 14
nevin2007
  • 1
  • 1

1 Answers1

1

The "Size on disk" is not readily available, but needs to be calculated based on dist block size. Since, os.stats(path).st_blksize wasn't available on my win10 machine, we need to get it via ctypes call instead.

import ctypes
from pathlib import Path
import math

fp = Path("E:/mylviing.JPG")

sectorsPerCluster = ctypes.c_ulonglong(0)
bytesPerSector = ctypes.c_ulonglong(0)
rootPathName = ctypes.c_wchar_p(fp.anchor)

ctypes.windll.kernel32.GetDiskFreeSpaceW(rootPathName,
    ctypes.pointer(sectorsPerCluster),
    ctypes.pointer(bytesPerSector),
    None,
    None,
)

cluster_size = bytesPerSector.value
size_on_disk = cluster_size * math.ceil(fp.stat().st_size * 1.0 / cluster_size)
print(size_on_disk)

Output: 208896

My test file was

  • size: 203 KB (208,498 bytes)
  • Size on disk: 204 KB (208,896 bytes)
Tzane
  • 2,752
  • 1
  • 10
  • 21
  • this not work when the object is a "file container", on my system : sectorsPerCluster : 8 bytesPerSector : 512 rootPathName : 42152368 so size on disk must be 32212254720 bytes but it is 28,232,646,656 bytes (see the attached picture) – nevin2007 Jul 17 '23 at 08:02