【问题标题】:How do I get the size of sub directory from a directory in python?如何从 python 中的目录获取子目录的大小?
【发布时间】:2018-02-06 17:41:37
【问题描述】:

以下是代码

import os
def get_size(path):
    total_size = 0
    for root, dirs, files in os.walk(path):
        for f in files:
            fp = os.path.join(root, f)
            total_size += os.path.getsize(fp)
    return total_size

for root,dirs,files in os.walk('F:\House'):
   print(get_size(dirs))

输出:

F:\House 21791204366
F:\House\house md 1832264906
F:\House\house md\house M D 1 1101710538
F:\House\Season 2 3035002265
F:\House\Season 3 3024588888
F:\House\Season 4 2028970391
F:\House\Season 5 3063415301
F:\House\Season 6 2664657424
F:\House\Season 7 3322229429
F:\House\Season 8 2820075762

我只需要主目录之后的子目录及其大小。我的代码一直到最后一个目录并写入它的大小。

举个例子:

F:\House 21791204366
F:\House\house md 1832264906
F:\House\house md\house M D 1 1101710538

它打印了house mdhouse M D 1house md 中的子目录)的大小。但我只想要它直到house md 子目录级别。

期望的输出: 我需要主目录级别(由用户指定)之后的每个子目录的大小,而不是子子目录(但它们的大小应包含在父目录中。)

我该怎么做?

【问题讨论】:

  • 我不明白你在问什么。您的示例输出具有 F:\House\house md\house M D 1 但您说您不想要它。期望的输出是什么?
  • 所需的输出 >> 我想要主目录级别之后的每个子目录的大小(由用户指定)而不是子子目录(但它们的大小应该包含在父目录中。)跨度>
  • edit您的问题包含所需的输出。

标签: python python-3.x filesystems


【解决方案1】:

打印每个直接子目录的大小和父目录的总大小类似于du -bcs */命令:

#!/usr/bin/env python3.6
"""Usage: du-bcs <parent-dir>"""
import os
import sys

if len(sys.argv) != 2:
    sys.exit(__doc__)  # print usage

parent_dir = sys.argv[1]
total = 0
for entry in os.scandir(parent_dir):
    if entry.is_dir(follow_symlinks=False): # directory
        size = get_tree_size_scandir(entry)
        # print the size of each immediate subdirectory
        print(size, entry.name, sep='\t')  
    elif entry.is_file(follow_symlinks=False): # regular file
        size = entry.stat(follow_symlinks=False).st_size
    else:
        continue
    total += size
print(total, parent_dir, sep='\t') # print the total size for the parent dir

在哪里get_tree_size_scandir()[text in Russian, code in Python, C, C++, bash]

这里的目录大小是其中所有常规文件及其子目录递归的外观大小。它不计算目录条目本身的大小或文件的实际磁盘使用量。相关:why is the output of du often so different from du -b.

【讨论】:

  • get_tree_size_scandir() 对我来说已经足够了。谢谢!!
【解决方案2】:

您可以将listdirisdir 结合使用,而不是在getpath 函数中使用os.walk

for file in os.listdir(path):
    if not os.path.isdir(file):
        # Do your stuff
        total_size += os.path.getsize(fp)

        ...

os.walk 会访问整个目录树,而listdir 只会访问当前目录中的文件。

但是,请注意,这不会将子目录的大小添加到目录大小中。因此,如果“第 1 季”有 5 个每个 100MB 的文件和 5 个每个 100MB 的目录,那么您的函数报告的大小将仅为 500MB。

提示:如果您还想添加子目录的大小,请使用递归。

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 1970-01-01
    • 2010-11-10
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2014-03-04
    • 1970-01-01
    相关资源
    最近更新 更多