Recursively Counting Code Lines in a Python Project: Difference between revisions
Jump to navigation
Jump to search
(Created page with "=Internal= =Overview= <syntaxhighlight lang='py'> import sys from pathlib import Path def fail(msg): print(f"[error]: {msg}") sys.exit(1) def lines_in_file(file: P...") |
|||
Line 1: | Line 1: | ||
=Internal= | =Internal= | ||
* [[Python Code Examples]] | |||
=Overview= | =Overview= | ||
<syntaxhighlight lang='py'> | <syntaxhighlight lang='py'> |
Latest revision as of 19:21, 21 June 2023
Internal
Overview
import sys
from pathlib import Path
def fail(msg):
print(f"[error]: {msg}")
sys.exit(1)
def lines_in_file(file: Path):
count = 0
with open(file, 'r') as f:
for line in f:
if line == '\n':
pass
count += 1
print(f'{file}: {count}')
return count
def count_lines_recursively(d: Path):
file_count = 0
line_count = 0
for f in d.iterdir():
if f.is_file() and f.name.endswith('.py'):
file_count += 1
line_count += lines_in_file(f)
elif f.is_dir():
if f.name == 'venv':
# ignore
continue
fc, lc = count_lines_recursively(f)
file_count += fc
line_count += lc
return file_count, line_count
def main():
p = Path(sys.argv[1])
if not p.is_dir():
fail(f'not a directory: {p}')
file_count, line_count = count_lines_recursively(p)
print(f'files: {file_count}, lines of code: {line_count}')
main()