Skip to content

Instantly share code, notes, and snippets.

@ssomnath
Last active January 23, 2020 21:08
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 ssomnath/4b786222b04ab6ad10a8820c023c211c to your computer and use it in GitHub Desktop.
Save ssomnath/4b786222b04ab6ad10a8820c023c211c to your computer and use it in GitHub Desktop.
Count lines in python project
import os
from collections import OrderedDict
def count_doc_lines(file_path, chars_per_line=120):
non_blank_count = 0
total_lines = 0
with open(file_path) as file_handle:
for line in file_handle:
curr = 1
if line.strip():
# 120 chars per line
curr += len(line) // chars_per_line
non_blank_count += curr
total_lines += curr
#return total_lines, non_blank_count
return non_blank_count
def count_code_lines(file_path):
non_blank_count = 0
total_lines = 0
with open(file_path) as file_handle:
for line in file_handle:
total_lines += 1
if line.strip():
# 120 chars per line
non_blank_count += 1
#return total_lines, non_blank_count
return non_blank_count
def count_lines_per_file_in_proj(root_dir, ignore_folders=['.eggs']):
doc_files = {}
code_files = {}
root_dir = os.path.abspath(root_dir)
for item in os.listdir(root_dir):
item_path = os.path.join(root_dir, item)
if os.path.isdir(item_path) and item not in ignore_folders:
#print('Folder of interest: ' + item)
sub_code, sub_doc = count_lines_in_proj(item_path)
code_files.update(sub_code)
doc_files.update(sub_doc)
else:
if item.endswith('.py'):
code_files[item_path] = count_code_lines(item_path)
elif item.endswith('.rst'):
doc_files[item_path] = count_doc_lines(item_path)
doc_files = OrderedDict(sorted(doc_files.items(), key=lambda x: x[1]))
code_files = OrderedDict(sorted(code_files.items(), key=lambda x: x[1]))
return code_files, doc_files
def count_lines_in_project(root_dir, ignore_folders=['.eggs']):
code, docs = count_lines_per_file_in_proj(root_dir, ignore_folders=ignore_folders)
return sum(list(code.values())), sum(list(docs.values()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment