Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count lines in files
#!/bin/python
"""
This utility allows you to count the number of lines in files
by default just .py files, but accepts command-line arguments.
This utility does miss files and folders beginning with '.'
so don't use them!
usage: {script} {path} [extensions] [exclude]
based on: https://stackoverflow.com/questions/38543709/count-lines-of-code-in-directory-using-python#answer-46329364
## Changelog
### 1.0
#### additions
- extensions cli argument
- exclude cli argument
- __main__ so can be run standalone
#### fixes
- python2 utf8 files
#### changes
- omits dot-file fs-entries
- renamed thing to fsentry everywhere
"""
import os
import io
import sys
def countlines(start, lines=0, header=True, begin_start=None, exts=None, exclude_begin=None):
if exts is None:
exts = ['.py']
if exclude_begin is None:
exclude_begin = []
if header:
print('{:>10} |{:>10} | {:<20}'.format('ADDED', 'TOTAL', 'FILE'))
print('{:->11}|{:->11}|{:->20}'.format('', '', ''))
for fsentry in os.listdir(start):
fsentry = os.path.join(start, fsentry)
if os.path.isfile(fsentry):
ext_match = False
for ext in exts:
if fsentry.endswith(ext):
ext_match = True
if ext_match:
with io.open(fsentry, encoding='utf-8') as f:
newlines = f.readlines()
newlines = len(newlines)
lines += newlines
if begin_start is not None:
reldir_of_fsentry = '.' + fsentry.replace(begin_start, '')
else:
reldir_of_fsentry = '.' + fsentry.replace(start, '')
print('{:>10} |{:>10} | {:<20}'.format(
newlines, lines, reldir_of_fsentry))
for fsentry in os.listdir(start):
fsentry = os.path.join(start, fsentry)
basename = os.path.basename(fsentry)
excluded = False
for exclusion in exclude_begin:
if basename.startswith(exclusion):
excluded = True
if os.path.isdir(fsentry) and not basename.startswith('.') and not excluded:
lines = countlines(
fsentry,
lines,
header=False,
begin_start=start,
exts=exts,
exclude_begin=exclude_begin)
return lines
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Must supply path")
exit(1)
exts=None
if len(sys.argv) > 2:
exts=sys.argv[2].split(',')
exclude=None
if len(sys.argv) > 3:
exclude = sys.argv[3].split(',')
if not os.path.exists(sys.argv[1]):
print("Must supply valid path")
exit(2)
total = countlines(sys.argv[1], exts=exts, exclude_begin=exclude)
print("{}".format(total))
@Lewiscowles1986

This comment has been minimized.

Copy link
Owner Author

Lewiscowles1986 commented Oct 7, 2018

may need to sudo ln -s ${which python} /bin/python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.