如何在Python中获取目录的大小?代码示例

2021年11月16日19:52:03 发表评论 682 次浏览

Python如何获取目录的大小?在 Python 中以字节为单位计算目录的大小,并使用 matplotlib 绘制饼图以查看哪个子目录的大小最大。

你有没有想过如何使用 Python 以字节为单位获取文件夹大小?你可能已经知道,os.path.get_size()函数只返回正确文件的正确大小,而不是文件夹。在本快速教程中,你将学习如何在 Python 中创建一个简单的函数来计算目录的总大小。

让我们开始吧,打开一个新的 Python 文件:

import os

下面的核心函数根据目录的相对或绝对路径计算目录的总大小:

def get_directory_size(directory):
    """Returns the `directory` size in bytes."""
    total = 0
    try:
        # print("[+] Getting the size of", directory)
        for entry in os.scandir(directory):
            if entry.is_file():
                # if it's a file, use stat() function
                total += entry.stat().st_size
            elif entry.is_dir():
                # if it's a directory, recursively call this function
                total += get_directory_size(entry.path)
    except NotADirectoryError:
        # if `directory` isn't a directory, get the file size then
        return os.path.getsize(directory)
    except PermissionError:
        # if for whatever reason we can't open the folder, return 0
        return 0
    return total

在以上的Python获取目录的大小示例中,请注意,我使用了os.scandir()函数,该函数返回给定目录中条目(文件或目录)的迭代器。

如果给定的路径不是文件夹(文件或链接),os.scandir()会引发NotADirectoryError,这就是我们捕获该异常并仅返回该文件的实际大小的原因。

如果它无法打开文件(例如系统文件),它也会引发PermissionError,在这种情况下,我们将只返回0。

如何在Python中获取目录的大小?上面的函数将返回以字节为单位的大小,这对于大目录当然是不可读的,因此,让我们创建一个函数来将这些字节缩放为 Kilo、Mega、Giga 等:

def get_size_format(b, factor=1024, suffix="B"):
    """
    Scale bytes to its proper byte format
    e.g:
        1253656 => '1.20MB'
        1253656678 => '1.17GB'
    """
    for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
        if b < factor:
            return f"{b:.2f}{unit}{suffix}"
        b /= factor
    return f"{b:.2f}Y{suffix}"

好的,我要在我的 C 盘上测试这个(我知道它很大):

get_size_format(get_directory_size("C:\\"))

这花了大约一分钟并返回以下内容:

'100.91GB'

Python获取目录的大小示例 - 现在,如果我想知道哪些子目录占用了大部分空间怎么办?好吧,下面的代码不只是计算每个子目录的大小,而是使用matplotlib库(你可以在其中安装使用pip3 install matplotlib)绘制一个饼图,显示每个子目录的大小:

import matplotlib.pyplot as plt

def plot_pie(sizes, names):
    """Plots a pie where `sizes` is the wedge sizes and `names` """
    plt.pie(sizes, labels=names, autopct=lambda pct: f"{pct:.2f}%")
    plt.title("Different Sub-directory sizes in bytes")
    plt.show()

if __name__ == "__main__":
    import sys
    folder_path = sys.argv[1]

    directory_sizes = []
    names = []
    # iterate over all the directories inside this path
    for directory in os.listdir(folder_path):
        directory = os.path.join(folder_path, directory)
        # get the size of this directory (folder)
        directory_size = get_directory_size(directory)
        if directory_size == 0:
            continue
        directory_sizes.append(directory_size)
        names.append(os.path.basename(directory) + ": " + get_size_format(directory_size))

    print("[+] Total directory size:", get_size_format(sum(directory_sizes)))
    plot_pie(directory_sizes, names)

现在,这将目录作为命令行中的参数:

python get_directory_size.py C:\

Python如何获取目录的大小?下面是结果,这将显示一个漂亮的馅饼,看起来像这样:

如何在Python中获取目录的大小?代码示例

现在看到这个图表后,我知道用户和Windows文件夹占用了我的大部分C驱动器!

如何在Python中获取目录的大小?好的,这是本教程的内容,如果你想了解有关在 Python 中处理文件和目录的更多信息,请查看本教程。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: