首页 > 解决方案 > 如何使用给定的跳过步骤获取目录的平均大小

问题描述

我有一个包含大量文件的目录,我想检查每第 n 个或固定数量的文件的大小,然后将其推断为该目录中的总文件数。

我尝试了一些东西,但我的精度和语法很糟糕。我绝不要求修复我的代码,它只是一个不起作用且看起来不错的示例。

我在 Python 2.7

def get_size2(path):
    files = os.listdir(path)
    filesCount = len(files)
    samples = 5.0
    step = math.ceil(filesCount / samples)
    files = files[0::step]
    reminderCount = filesCount - len(files)
    reminderStep = float(reminderCount / len(files)) + 1
    total_size = 0
    for f in files:
        fp = os.path.join(path, f)
        if not os.path.islink(fp):
            total_size += os.path.getsize(fp) * reminderStep
    return int(total_size)

标签: python

解决方案


鉴于代码,很难完全理解您正在尝试做什么,但我认为您希望根据子样本中的平均值收集估计的目录大小。

您可以通过将第三个参数传递给 for 循环来迭代给定特定增量大小的文件:

for count in range(0, len(files), samples):
    print(f"On count: {count}")

另外,remindCount 和remindStep 变量让我有点迷茫。

本质上,您想评估您查看的文件的平均大小(您查看的总大小,除以您查看的文件总数)您可以将平均文件大小乘以目录中的文件数来推断样本的预期目录大小是多少。将上述逻辑转换为函数会将问题简化为以下内容:

import os
import math

def get_size2(path):
    files = os.listdir(path)
    filesCount = len(files)
    samples = 1
    files_counted = 0
    total_size = 0
    for count in range(0, len(files), samples):
        files_counted += 1
        f = files[count]
        fp = os.path.join(path, f)
        if not os.path.islink(fp):
            total_size += os.path.getsize(fp)
    return int(total_size / files_counted) * filesCount

def main():
    print(f'{get_size2("./test/path")}')

if __name__ == "__main__":
    main()

这试图保留与您发布的一样多的变量和结构,同时调整示例的逻辑。我建议对代码进行一些更改,例如将样本大小作为参数传递。


推荐阅读