Last active
October 3, 2019 00:37
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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