تمرين إعادة البناء
ماسح أحجام المجلدات
احسب أحجام المجلدات واعرضها مرتبة بصيغة مقروءة.
python
~20 دقيقة
مبتدئ
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
import argparse
from pathlib import Path
def folder_size(folder: Path) -> int:
total = 0
for path in folder.rglob("*"):
if path.is_file():
try:
total += path.stat().st_size
except OSError:
pass
return total
def human_size(size: int) -> str:
units = ["B", "KB", "MB", "GB", "TB"]
amount = float(size)
for unit in units:
if amount < 1024 or unit == units[-1]:
return f"{amount:.1f} {unit}"
amount /= 1024
return f"{size} B"
def scan(root: Path) -> list[tuple[int, Path]]:
folders = [path for path in root.iterdir() if path.is_dir()]
return sorted(((folder_size(folder), folder) for folder in folders), reverse=True)
def main() -> None:
parser = argparse.ArgumentParser(description="Show direct child folder sizes.")
parser.add_argument("root", nargs="?", type=Path, default=Path("."))
args = parser.parse_args()
for size, folder in scan(args.root):
print(f"{human_size(size):>10} {folder}")
if __name__ == "__main__":
main()اكتب هنا