脚本如何统计文件夹大小

wen 实用脚本 29

本文目录导读:

脚本如何统计文件夹大小

  1. Linux/Mac 命令行
  2. Shell 脚本
  3. Python 脚本
  4. 更高效的 Python 版本(使用 os.walk)
  5. Windows PowerShell
  6. 跨平台 Node.js 脚本
  7. 使用建议

Linux/Mac 命令行

使用 du 命令

# 统计当前目录大小(人类可读格式)
du -sh .
# 统计指定文件夹大小
du -sh /path/to/folder
# 统计所有子文件夹的大小
du -sh * /
# 按大小排序显示
du -sh * | sort -rh

使用 ncdu(更友好的交互式工具)

# 安装
sudo apt install ncdu  # Ubuntu
brew install ncdu       # Mac
# 使用
ncdu /path/to/folder

Shell 脚本

#!/bin/bash
# folder_size.sh
target_dir="${1:-.}"  # 默认当前目录
if [ -d "$target_dir" ]; then
    echo "统计文件夹: $target_dir"
    echo "大小: $(du -sh "$target_dir" | cut -f1)"
    echo "文件数: $(find "$target_dir" -type f | wc -l)"
    echo "目录数: $(find "$target_dir" -type d | wc -l)"
else
    echo "错误: 文件夹不存在"
    exit 1
fi

Python 脚本

# folder_size.py
import os
import sys
from pathlib import Path
def get_folder_size(folder_path):
    """递归计算文件夹大小"""
    total_size = 0
    folder = Path(folder_path)
    if not folder.exists():
        print(f"错误: 文件夹 {folder_path} 不存在")
        return None
    for item in folder.rglob('*'):
        if item.is_file():
            try:
                total_size += item.stat().st_size
            except (OSError, PermissionError):
                pass
    return total_size
def format_size(size_bytes):
    """格式化文件大小"""
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size_bytes < 1024:
            return f"{size_bytes:.2f} {unit}"
        size_bytes /= 1024
    return f"{size_bytes:.2f} PB"
if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else "."
    size = get_folder_size(target)
    if size is not None:
        print(f"文件夹: {target}")
        print(f"大小: {format_size(size)}")
        # 显示文件/目录数量
        folder = Path(target)
        files = sum(1 for _ in folder.rglob('*') if _.is_file())
        dirs = sum(1 for _ in folder.rglob('*') if _.is_dir())
        print(f"文件数: {files}")
        print(f"目录数: {dirs}")

更高效的 Python 版本(使用 os.walk)

import os
import sys
def get_folder_size_fast(folder_path):
    """使用 os.walk 快速计算"""
    total_size = 0
    file_count = 0
    dir_count = 0
    if not os.path.exists(folder_path):
        print(f"错误: 文件夹 {folder_path} 不存在")
        return None
    for dirpath, dirnames, filenames in os.walk(folder_path):
        dir_count += 1
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                total_size += os.path.getsize(fp)
                file_count += 1
            except (OSError, FileNotFoundError):
                pass
    return total_size, file_count, dir_count
# 使用示例
if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else "."
    result = get_folder_size_fast(target)
    if result:
        size, files, dirs = result
        # 格式化输出
        print(f"文件夹: {target}")
        print(f"大小: {size/1024/1024:.2f} MB")
        print(f"文件数: {files}")
        print(f"目录数: {dirs}")

Windows PowerShell

# 统计文件夹大小
$folder = "C:\Path\To\Folder"
$size = (Get-ChildItem -Path $folder -Recurse | Measure-Object -Property Length -Sum).Sum
Write-Host "文件夹大小: $(($size / 1MB).ToString('F2')) MB"
# 或者使用更详细的脚本
function Get-FolderSize {
    param([string]$Path = ".")
    $items = Get-ChildItem -Path $Path -Recurse
    $size = ($items | Measure-Object -Property Length -Sum).Sum
    $files = ($items | Where-Object {!$_.PSIsContainer}).Count
    $dirs = ($items | Where-Object {$_.PSIsContainer}).Count
    Write-Host @"
文件夹: $Path
大小: $(($size / 1MB).ToString('F2')) MB
文件数: $files
目录数: $dirs
"@
}
Get-FolderSize "C:\YourFolder"

跨平台 Node.js 脚本

// folder_size.js
const fs = require('fs');
const path = require('path');
function getFolderSize(folderPath) {
    let totalSize = 0;
    let files = 0;
    let dirs = 0;
    function walk(dir) {
        const items = fs.readdirSync(dir);
        dirs++;
        items.forEach(item => {
            const fullPath = path.join(dir, item);
            const stat = fs.statSync(fullPath);
            if (stat.isDirectory()) {
                walk(fullPath);
            } else {
                totalSize += stat.size;
                files++;
            }
        });
    }
    walk(folderPath);
    return { size: totalSize, files, dirs };
}
// 使用
const result = getFolderSize('.');
console.log(`大小: ${(result.size / 1024 / 1024).toFixed(2)} MB`);
console.log(`文件: ${result.files}, 目录: ${result.dirs}`);

使用建议

  • 快速统计:使用 du -sh 命令
  • 详细统计:使用 Python 或 Node.js 脚本
  • 交互式查看:使用 ncdu 工具
  • 跨平台:使用 Python 脚本(几乎任何系统都支持)

选择哪种方法取决于你的具体需求和操作系统环境。

抱歉,评论功能暂时关闭!