如何在Python中获取文件在磁盘上的实际大小?(它在硬盘上占用的实际空间大小)。
如何在Python中获取文件在磁盘上的实际大小?(它在硬盘上占用的实际空间大小)。
仅限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
st_blocks
已设置的平台:import os
def size_on_disk(path):
st = os.stat(path)
return st.st_blocks * 512
其他答案指出应该乘以os.stat(path).st_blksize
或os.vfsstat(path).f_bsize
是错误的。
Python文档中对os.stat_result.st_blocks
的描述非常清楚:
st_blocks
文件分配的512字节块数。当文件有空洞时,这可能比st_size
/512小。
此外,stat(2)
man页面也说明了同样的事情:
blkcnt_t st_blocks; /* Number of 512B blocks allocated */
num_blocks = os.stat(filename).st_blocks
block_size = os.statvfs(filename).f_bsize
sizeOnDisk = num_blocks*block_size
statvfs
模块,但是答案使用了os
模块。正如您所看到的,Python 3的文档显示os.statvfs
仍然存在,并且甚至在Python 3.6中更新以包括新功能。 - bytesizeddd if=/dev/zero of=testsize bs=1 count=419472426
创建一个文件。换句话说,使用du的--apparent-size选项得出的结果与实际值相差7,126而不是4,096。请注意:使用du的--apparent-size选项得出的值与os.stat(filename).st_size
获得的值相匹配。 - user1748155实际上已经过去了12年,但至今没有关于如何在Windows上完成此操作的答案...
以下是通过ctypes在Windows上查找“磁盘空间大小”的方法:
import ctypes
def GetSizeOnDisk(path):
'''https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getcompressedfilesizew'''
filesizehigh = ctypes.c_ulonglong(0) # not sure about this... something about files >4gb
return ctypes.windll.kernel32.GetCompressedFileSizeW(ctypes.c_wchar_p(path),ctypes.pointer(filesizehigh))
'''
>>> os.stat(somecompressedorofflinefile).st_size
943141
>>> GetSizeOnDisk(somecompressedorofflinefile)
671744
>>>
'''
st = os.stat(…)
du = st.st_blocks * st.st_blksize
st.st_blocks
始终以512字节为单位,而st.st_blksize
是文件系统块大小(通常为4096字节)。真正的用法是 st.st_blocks * 512
。请参阅 http://linux.die.net/man/2/stat 了解更多详细信息。 - Jim Paris我不确定这是磁盘上的大小还是逻辑大小:
import os
filename = "/home/tzhx/stuff.wev"
size = os.path.getsize(filename)
如果这不是你要找的机器人,你可以通过将其除以集群大小(作为浮点数),然后使用 ceil 函数向上取整,最后再乘回来。
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)
。