# 指定パスのフォルダ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)