在Python中确定文件系统的簇大小 [英] Determine cluster size of file system in Python

查看:308
本文介绍了在Python中确定文件系统的簇大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算Python中文件的 大小 。因此,我想确定存储文件的文件系统的簇大小。



如何确定Python中的簇大小?
或另一种计算 大小的内置方法 也可以。



我看了 os.path.getsize ,但它返回的文件大小以字节为单位,没有考虑到FS的块大小。

我希望这可以以独立于操作系统的方式完成...

在UNIX / Linux平台上,使用Python内建的 /os.html#os.statvfsrel =nofollow noreferrer> os.statvfs 。在Windows上,除非您可以找到第三方库,否则您需要使用ctypes来调用Win32函数 GetDiskFreeSpace ,像这样:

  import ctypes 

sectorsPerCluster = ctypes.c_ulonglong(0)
bytesPerSector = ctypes.c_ulonglong(0)
rootPathName = ctypes.c_wchar_p(uC:\\\)

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


print(sectorsPerCluster.value,bytesPerSector.value)



请注意,ctypes只是成为2.5或2.6中的Python stdlib的一部分(不记得是哪一个)。

我把这种东西放在一个函数中首先检查是否存在UNIX变体,如果(大概是因为它是r在Windows上unning)不。这样,如果Python在Windows上执行statvfs,它就会使用它。


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 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.

这篇关于在Python中确定文件系统的簇大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆