萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Python 遞迴計算指定路徑下所有目錄大小腳本實作

需求背景

系統管理與磁碟空間分析常需統計各目錄佔用大小。Python 透過 os.walk() 遍歷目錄樹,結合 os.path.getsize() 即可實作目錄大小統計工具。本文提供完整腳本並優化效能與錯誤處理。

基礎版實作

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
計算指定路徑下所有子目錄大小
用法: python dir_size.py /path/to/target
"""

import os
import sys
from os.path import getsize, join

def get_dir_size(root_dir):
    """遞迴計算單一目錄總大小 (位元組)"""
    total_size = 0
    try:
        for dirpath, dirnames, filenames in os.walk(root_dir):
            for filename in filenames:
                filepath = join(dirpath, filename)
                try:
                    # 忽略符號連結避免重複計算
                    if not os.path.islink(filepath):
                        total_size += getsize(filepath)
                except (OSError, FileNotFoundError):
                    # 檔案可能被刪除或無權限
                    pass
    except PermissionError:
        print(f"權限不足: {root_dir}", file=sys.stderr)
    return total_size

def list_subdir_sizes(root_dir):
    """列出指定目錄下所有一級子目錄大小"""
    if not os.path.isdir(root_dir):
        print(f"錯誤: {root_dir} 不是有效目錄", file=sys.stderr)
        return
    
    print(f"{'目錄名稱':<40} {'大小 (KB)':>12} {'大小 (MB)':>12} {'大小 (GB)':>12}")
    print("-" * 80)
    
    for item in sorted(os.listdir(root_dir)):
        item_path = join(root_dir, item)
        if os.path.isdir(item_path) and not os.path.islink(item_path):
            size_bytes = get_dir_size(item_path)
            size_kb = size_bytes / 1024
            size_mb = size_kb / 1024
            size_gb = size_mb / 1024
            print(f"{item:<40} {size_kb:>12.2f} {size_mb:>12.2f} {size_gb:>12.2f}")

if __name__ == '__main__':
    target = sys.argv[1] if len(sys.argv) > 1 else '.'
    list_subdir_sizes(target)

進階版:加入快取、平行處理、人性化輸出

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
進階目錄大小分析工具
功能: 平行計算、快取結果、多種輸出格式、排序、過濾
"""

import os
import sys
import argparse
import json
import concurrent.futures
from pathlib import Path
from functools import lru_cache
from os.path import getsize, join

@lru_cache(maxsize=1024)
def get_dir_size_cached(path):
    """帶快取的目錄大小計算"""
    total = 0
    try:
        for dirpath, dirnames, filenames in os.walk(path):
            for fname in filenames:
                fpath = join(dirpath, fname)
                if not os.path.islink(fpath):
                    try:
                        total += getsize(fpath)
                    except OSError:
                        pass
    except PermissionError:
        pass
    return total

def human_size(bytes_size):
    """位元組轉人類可讀格式"""
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if bytes_size < 1024:
            return f"{bytes_size:.2f} {unit}"
        bytes_size /= 1024
    return f"{bytes_size:.2f} PB"

def scan_directory(root, max_workers=4, min_size=0, sort_by='size', reverse=True):
    """平行掃描目錄"""
    root = Path(root).resolve()
    dirs = [d for d in root.iterdir() if d.is_dir() and not d.is_symlink()]
    
    results = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_dir = {executor.submit(get_dir_size_cached, str(d)): d for d in dirs}
        for future in concurrent.futures.as_completed(future_to_dir):
            dir_path = future_to_dir[future]
            try:
                size = future.result()
                if size >= min_size:
                    results.append((dir_path.name, size))
            except Exception as e:
                print(f"錯誤 {dir_path}: {e}", file=sys.stderr)
    
    # 排序
    if sort_by == 'size':
        results.sort(key=lambda x: x[1], reverse=reverse)
    elif sort_by == 'name':
        results.sort(key=lambda x: x[0].lower(), reverse=reverse)
    
    return results

def main():
    parser = argparse.ArgumentParser(description='目錄大小分析工具')
    parser.add_argument('path', nargs='?', default='.', help='掃描目錄 (預設: 當前目錄)')
    parser.add_argument('-j', '--jobs', type=int, default=4, help='平行執行緒數')
    parser.add_argument('--min-mb', type=float, default=0, help='最小顯示大小 (MB)')
    parser.add_argument('--sort', choices=['size', 'name'], default='size', help='排序方式')
    parser.add_argument('--asc', action='store_true', help='升序排列')
    parser.add_argument('--json', action='store_true', help='輸出 JSON 格式')
    parser.add_argument('--csv', action='store_true', help='輸出 CSV 格式')
    
    args = parser.parse_args()
    
    min_bytes = int(args.min_mb * 1024 * 1024)
    results = scan_directory(
        args.path, 
        max_workers=args.jobs,
        min_size=min_bytes,
        sort_by=args.sort,
        reverse=not args.asc
    )
    
    if args.json:
        print(json.dumps([{'name': n, 'size_bytes': s, 'size_human': human_size(s)} 
                         for n, s in results], ensure_ascii=False, indent=2))
    elif args.csv:
        print("name,size_bytes,size_human")
        for name, size in results:
            print(f'"{name}",{size},"{human_size(size)}"')
    else:
        print(f"{'目錄名稱':<50} {'大小':>15}")
        print("-" * 68)
        for name, size in results:
            print(f"{name:<50} {human_size(size):>15}")

if __name__ == '__main__':
    main()

使用範例

# 基礎掃描當前目錄
python dir_size.py

# 掃描指定目錄,4 執行緒,只顯示 >100MB 的目錄,按大小降序
python dir_size_advanced.py /var/www -j 4 --min-mb 100

# 輸出 JSON 供其他程式處理
python dir_size_advanced.py /home/user --json > dir_sizes.json

# CSV 匯入試算表
python dir_size_advanced.py /data --csv > sizes.csv

效能優化重點

  1. 忽略符號連結:os.path.islink() 避免循環掃描與重複計算
  2. 例外處理:捕捉 PermissionError、FileNotFoundError 避免中斷
  3. 快取機制:@lru_cache 避免重複計算同一目錄 (適用多次執行)
  4. 平行處理:ThreadPoolExecutor 利用 I/O 等待時間並行統計多目錄
  5. Pathlib:現代物件導向路徑操作,程式碼更清晰

替代方案:系統工具

若僅需快速查看,系統內建工具更高效:

  • Linux/macOS: du -h --max-depth=1 /path | sort -hr
  • Windows: dir /s 或 PowerShell Get-ChildItem -Recurse | Measure-Object -Property Length -Sum
  • 跨平台 GUI: ncdu (互動式)、WinDirStat
copyright © 萬盛學電腦網 all rights reserved