如何在Python中找到文件容器在磁盘上的大小?请注意,我无法使用簇大小来计算磁盘上的大小,因为容器可能有空空间(见图)
size : 32,212,254,720 bytes
size on disk : 28,232,646,656 bytes
我的操作系统是Windows并使用Python 3.8
“磁盘上的大小”不容易获得,但需要根据 dist 块大小计算。由于,
os.stats(path).st_blksize
在我的win10机器上不可用,我们需要通过ctypes调用来获取它。
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 * sectorsPerCluster.value
size_on_disk = cluster_size * math.ceil(fp.stat().st_size * 1.0 / cluster_size)
print(size_on_disk)
输出:
208896
我的测试文件是