← all snippets

count-lines

Counts total lines across every file matching a glob pattern under the current directory. A quick, dependency-free stand-in for "how big is this codebase/log set".

Python 3 #05

Source

count-lines.py
#!/usr/bin/env python3
"""Count total lines across files matching a glob pattern (relative to cwd)."""
import sys
from pathlib import Path

if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: count-lines.py '<glob-pattern>'  (e.g. 'src/**/*.py')")
    total = 0
    for p in Path(".").glob(sys.argv[1]):
        if p.is_file():
            with open(p, "rb") as f:
                total += sum(1 for _ in f)
    print(total)

Input

patternstring — positional argument, a glob pattern relative to the current directory, e.g. src/**/*.py (quote it so the shell doesn't expand it first)

Output

Prints a single integer: the total line count summed across every matching file. Prints 0 if nothing matches.

Usage

$ python3 count-lines.py 'src/**/*.py'
4218

Config

No configuration required.

Security notes

  • Uses pathlib.Path.glob, not shell expansion, so unquoted-glob shell injection isn't a concern.
  • Files are read in binary mode and counted by newline byte, avoiding encoding-related crashes on mixed-encoding trees.