Skip to content

Instantly share code, notes, and snippets.

@shao-wang-me
Last active October 3, 2019 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shao-wang-me/a117bf14c0ad3dd467fc9bbb953683eb to your computer and use it in GitHub Desktop.
Save shao-wang-me/a117bf14c0ad3dd467fc9bbb953683eb to your computer and use it in GitHub Desktop.
Print number of lines of all files in a directory (default is the currect directory) and its subdirectories.
"""Print number of lines of all files in a directory (default is the currect directory) and its subdirectories.
"""
import os
import sys
def count_file_lines(filepath):
"""Count lines in a file
"""
lines = 0
with open(filepath) as f:
for i, line in enumerate(f):
lines += 1
return lines
def count_dir_lines(root, extensions=['py', 'java', 'groovy', 'sql']):
"""Count lines in a directory recursively
:param root: path of the directory
:param extensions: extensions of files to search for
:returns: number of lines
"""
extensions = tuple('.' + e for e in extensions)
lines = 0
for dirpath, dirnames, filenames in os.walk(root):
for filename in filenames:
if filename.lower().endswith(extensions):
lines += count_file_lines(dirpath + '/' + filename)
return lines
if __name__ == "__main__":
root = sys.argv[1] if len(sys.argv) > 1 else '.'
print('Count lines in', root)
print(count_dir_lines(root))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment