Skip to content

Instantly share code, notes, and snippets.

@samuraisam
Created May 30, 2012 21:33
Show Gist options
  • Save samuraisam/2839094 to your computer and use it in GitHub Desktop.
Save samuraisam/2839094 to your computer and use it in GitHub Desktop.
Recursive line count
#!/usr/bin/env python
"""Counts all the lines from a directory inward."""
import os
import os.path
import sys
lines = 0
# put the directories you want to search here
dirs = ['.']
# put the file types you want to recognize here
ftypes = set(['.py', '.html', '.m', '.h', '.c', '.cpp'])
bold = os.name == 'posix' and os.popen('tput bold').read() or ''
reset = os.name == 'posix' and os.popen('tput sgr0').read() or ''
for d in dirs:
for root, dirs, files in os.walk(os.path.join(os.getcwd(), d)):
lines_in_dir = 0
for name in files:
if os.path.splitext(os.path.basename(name))[1] in ftypes:
lines_in_dir += len(open(os.path.join(root, name), 'rU').readlines())
in_dir = root.replace(os.getcwd(), '') and root.replace(os.getcwd(), '') or '.'
if lines_in_dir > 0:
print ' %-6i in %s' % (lines_in_dir, in_dir.lstrip('/'))
lines += lines_in_dir
sys.stdout.write(bold)
print ' %-6i total lines' % (lines)
sys.stdout.write(reset)
@samuraisam
Copy link
Author

Example output

567    in .
372    in ./config
480    in ./mirrio
2037   in ./mirrio/api
460    in ./mirrio/api/cass_migrations
5014   in ./mirrio/api/db
121    in ./mirrio/api/fields
1679   in ./mirrio/api/handlers
1293   in ./mirrio/api/handlers/tests
770    in ./mirrio/api/helpers
55     in ./mirrio/api/management/commands
9      in ./mirrio/api/managers
4437   in ./mirrio/api/migrations
571    in ./mirrio/api/models
196    in ./mirrio/api/templates
151    in ./mirrio/api/templates/oauth
408    in ./mirrio/api/test
408    in ./mirrio/api/tests
1197   in ./mirrio/api/utils
82     in ./mirrio/api/utils/tests
786    in ./mirrio/apidocs/build/html
1254   in ./mirrio/apidocs/build/html/rest
321    in ./mirrio/scripts
22668  total lines

@samuraisam
Copy link
Author

I wrote this years and years ago and have always used it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment