Skip to content

Instantly share code, notes, and snippets.

@curegit
Last active April 1, 2024 10:24
Show Gist options
  • Save curegit/bcf9699081b673621db8209ed8f6ef61 to your computer and use it in GitHub Desktop.
Save curegit/bcf9699081b673621db8209ed8f6ef61 to your computer and use it in GitHub Desktop.
ディレクトリツリーに存在する拡張子を集計するスクリプト
#!/usr/bin/env python3
import sys
import os
from pathlib import Path
from collections import Counter
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def main():
try:
if len(sys.argv) == 1:
path = Path(".")
elif len(sys.argv) == 2:
path = Path(sys.argv[1])
else:
eprint("Usage: ./extstats.py [DIR]")
return 1
try:
path = path.resolve(strict=True)
if not path.is_dir():
raise RuntimeError()
except Exception:
eprint("No such directory")
return 1
files = (p for p in path.rglob("*", case_sensitive=False) if p.is_file())
exts = (f.suffix.lower() for f in files)
counts = Counter(exts)
for ext, count in sorted(counts.items(), key=lambda t: t[1], reverse=True):
try:
print(f"{ext}\t{count}", flush=True)
except BrokenPipeError:
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
return 128 + 13
except KeyboardInterrupt:
return 128 + 2
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment