pyhton,获取文件容器在磁盘上的大小

问题描述 投票:0回答:1

如何在Python中找到文件容器在磁盘上的大小?请注意,我无法使用簇大小来计算磁盘上的大小,因为容器可能有空空间(见图)

size : 32,212,254,720 bytes

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

我的操作系统是Windows并使用Python 3.8

view the image

python python-3.x
1个回答
1
投票

“磁盘上的大小”不容易获得,但需要根据 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

我的测试文件是

  • 大小:203 KB(208,498 字节)
  • 磁盘大小:204 KB(208,896 字节)
© www.soinside.com 2019 - 2024. All rights reserved.