Windows系统下Python3.8获取文件容器磁盘占用大小的方法
在Python 3.8(Windows)中获取文件容器的实际磁盘占用大小
针对你需要获取文件容器实际磁盘占用大小(即资源管理器中显示的size on disk)的需求,由于容器内部存在空余空间(通常表现为稀疏文件),无法通过簇大小计算准确值,以下是两种基于Windows系统API的实现方案:
方案1:使用标准库ctypes(无需额外安装)
通过调用Windows原生API GetCompressedFileSizeW,直接获取文件在磁盘上的实际占用字节数,该API会自动处理稀疏、压缩等特殊文件类型:
import ctypes from ctypes import wintypes def get_size_on_disk(file_path): # 调用Windows API GetCompressedFileSizeW high_dword = wintypes.DWORD() low_dword = ctypes.windll.kernel32.GetCompressedFileSizeW(file_path, ctypes.byref(high_dword)) # 处理API调用错误 if low_dword == 0xFFFFFFFF and ctypes.GetLastError() != 0: raise ctypes.WinError() # 拼接高低位得到完整大小 return (high_dword.value << 32) | low_dword # 示例使用 if __name__ == "__main__": target_file = r"C:\your\container\path\file.vhd" try: actual_size = get_size_on_disk(target_file) print(f"size on disk : {actual_size:,} bytes") except Exception as e: print(f"获取失败:{e}")
方案2:使用pywin32库(需先安装)
pywin32封装了Windows系统API,代码更简洁易读:
- 先安装依赖:
pip install pywin32
- 实现代码:
import win32file def get_size_on_disk(file_path): # 获取压缩/实际占用大小 size_low, size_high = win32file.GetCompressedFileSize(file_path) return (size_high << 32) | size_low # 示例使用 if __name__ == "__main__": target_file = r"C:\your\container\path\file.vhd" actual_size = get_size_on_disk(target_file) print(f"size on disk : {actual_size:,} bytes")
说明
两种方案均直接调用Windows系统接口,返回结果与资源管理器中显示的size on disk完全一致,无需手动计算簇大小,完美适配存在内部空余空间的文件容器场景。
内容的提问来源于stack exchange,提问作者nevin2007
相关产品推荐
相关产品推荐

