开发者

Determine cluster size of file system in Python

开发者 https://www.devze.com 2022-12-23 23:24 出处:网络
I would like to calculate the \"size on disk\" of a file in Python.Therefore I would like to determine the cluster size of the file system where the file is stored.

I would like to calculate the "size on disk" of a file in Python. Therefore I would like to determine the cluster size of the file system where the file is stored.

How do I determine the cluster size in Python? Or another built-in method that calculates the "size on disk" will also work.

I looked at os.path.getsize but it returns the file size in bytes, not taking开发者_StackOverflow the FS's block size into consideration.

I am hoping that this can be done in an OS independent way...


On UNIX/Linux platforms, use Python's built-in os.statvfs. On Windows, unless you can find a third-party library that does it, you'll need to use ctypes to call the Win32 function GetDiskFreeSpace, like this:

import ctypes

sectorsPerCluster = ctypes.c_ulonglong(0)
bytesPerSector = ctypes.c_ulonglong(0)
rootPathName = ctypes.c_wchar_p(u"C:\\")

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

print(sectorsPerCluster.value, bytesPerSector.value)

Note that ctypes only became part of the Python stdlib in 2.5 or 2.6 (can't remember which).

I put this sort of thing in a function that first checks whether the UNIX variant is present, and falls back to ctypes if (presumably because it's running on Windows) not. That way, if Python ever does implement statvfs on Windows, it will just use that.


Use statvfs, at least if you're aiming for a pre-3.0 version of Python. Not sure what it has been replaced with.

I also think you're going to have to do the maths yourself, Python doesn't seem to expose the "size in blocks" of files.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号