0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】指定パスのフォルダ1階層だけをリストアップし、そのフォルダのサイズと合わせてカンマ区切りで出力する

Last updated at Posted at 2025-09-05

ストレージの掃除をしたくて作った

  • どこのフォルダが容量を圧迫しているのかアタリをつけたくて作った
  • 指定パスのフォルダ1階層だけをリストアップし、そのフォルダのサイズと合わせてカンマ区切りで出力する
  • 出力結果をExcelに入れて容量が大きそうなフォルダを掃除する
  • Excelに貼り付けた後でソートするのも面倒なのでPython側でソートさせた

コード

# 指定パスのフォルダ1階層だけをリストアップし、そのフォルダのサイズと合わせてカンマ区切りで出力する
# 出力結果をExcelに入れて容量が大きそうなフォルダを掃除する

import os

def get_folder_size(path):
    total_size=0
    for dirpath ,dirname, filenames in os.walk(path):
        for f in filenames:
            try:
                fp=os.path.join(dirpath,f)
                total_size += os.path.getsize(fp)
            except OSError:
                pass
    return total_size

def main_(target_path):
    # 指定パスを出力
    print(f"target_path,{target_path}")

    # エスケープ対策
    target_path = target_path.replace("\\","\\\\")
    
    # フォルダサイズ情報を格納
    get_folder_sizes = []

    for item in os.listdir(target_path):
        full_path = os.path.join(target_path,item)
        if os.path.isdir(full_path):
            size_bytes = get_folder_size(full_path)
            size_mb = int(size_bytes / (1024^2))
            get_folder_sizes.append((item,size_mb))

    # 総サイズ(MB)
    total_size = sum(size for _, size in get_folder_sizes)
    print(f"total_size,{total_size}")
    print() #空行はさむ

    # 大きい順にソート
    get_folder_sizes.sort(key=lambda x: x[1], reverse=True)

    # カンマ区切り出力
    print("Folder_Name, Size(MB),Percent_of_Total")
    for name, size in get_folder_sizes:
        percent = (size/total_size * 100) if total_size > 0 else 0
        print(f"{name},{size:.2f},{percent:.2f}%")

# 調べたいフォルダパス
Target_Path = r"C:\Program Files"

main_(Target_Path)


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?