获取文件的实际磁盘空间

时间:2010-11-25 08:12:25

标签: python

如何在python中获取磁盘上的实际文件大小? (它在硬盘上的实际大小)。

6 个答案:

答案 0 :(得分:16)

仅限UNIX:

import os
from collections import namedtuple

_ntuple_diskusage = namedtuple('usage', 'total used free')

def disk_usage(path):
    """Return disk usage statistics about the given path.

    Returned valus is a named tuple with attributes 'total', 'used' and
    'free', which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return _ntuple_diskusage(total, used, free)

用法:

>>> disk_usage('/')
usage(total=21378641920, used=7650934784, free=12641718272)
>>>

编辑1 - 也适用于Windows:https://code.activestate.com/recipes/577972-disk-usage/?in=user-4178764

编辑2 - 这在Python 3.3+中也可用:https://docs.python.org/3/library/shutil.html#shutil.disk_usage

答案 1 :(得分:4)

使用os.stat(filename).st_size获取文件的逻辑大小。使用os.statvfs(filename).f_bsize获取文件系统块大小。然后使用整数除法计算磁盘上的正确大小,如下所示:

lSize=os.stat(filename).st_size
bSize=os.statvfs(filename).f_bsize
sizeOnDisk=(lSize/bSize+1)*bSize

答案 2 :(得分:2)

st = os.stat(…)
du = st.st_blocks * st.st_blksize

答案 3 :(得分:0)

我不确定这是磁盘大小还是逻辑大小:

import os
filename = "/home/tzhx/stuff.wev"
size = os.path.getsize(filename)

如果它不是您要寻找的机器人,您可以通过除以簇大小(浮点数),然后使用ceil,然后乘以来将其四舍五入。

答案 4 :(得分:0)

要获取给定文件/文件夹的磁盘使用情况,您可以执行以下操作:

import os

def disk_usage(path):
    """Return cumulative number of bytes for a given path."""
    # get total usage of current path
    total = os.path.getsize(path)
    # if path is dir, collect children
    if os.path.isdir(path):
        for file_name in os.listdir(path):
            child = os.path.join(path, file_name)
            # recursively get byte use for children
            total += disk_usage(child)
    return total

该函数以递归方式收集嵌套在给定路径中的文件的字节使用情况,并返回整个路径的累计用量。 如果您希望打印每个文件的信息,也可以在其中添加print "{path}: {bytes}".format(path, total)

答案 5 :(得分:0)

在设置了st_blocks的平台上,这是在磁盘上获取文件大小的正确方法:

import os

def size_on_disk(path):
    st = os.stat(path)
    return st.st_blocks * 512

其他表示乘以os.stat(path).st_blksizeos.vfsstat(path).f_bsize的答案完全是错误的。

Python documentation for os.stat_result.st_blocks非常清楚地声明:

  

st_blocks
  为文件分配的512字节块数。文件有孔时,它可能小于st_size / 512。

此外,stat(2) man page说了同样的话:

blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */