Skip to content

Instantly share code, notes, and snippets.

@Pranavraut033
Last active January 23, 2023 11:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Pranavraut033/23f98ad00d89361a8706cb5d27986f9e to your computer and use it in GitHub Desktop.
Save Pranavraut033/23f98ad00d89361a8706cb5d27986f9e to your computer and use it in GitHub Desktop.
Lines of code (LOC) counter in python
import os
# count lines from this extenstions
extenstions = [
".php",
".html",
".js",
".vue",
".css",
".jade",
".sass",
".scss",
".env",
".xml",
".java",
".kt",
".json",
".bat",
".gradle",
# ...
]
# do not count these files/folders
skipThese = [
"lib",
"node_modules",
"dist",
"build",
"libraries",
".idea",
"package-lock.json",
"ckeditor",
]
def getcount(folder):
"""
params: folder name in the pwd
returns (file count, total line count)
"""
fi, count = 0, 0 # initial gobal count to 0
# traverse each item in folder given as parameter
for file in os.listdir(folder):
file_path = os.path.join(folder, file)
# check if it's not in do not count list
if str(file) in skipThese:
continue
# Check if the current item is a folder
if os.path.isdir(file_path):
# recursively call getcount function
c, fi1 = getcount(file_path)
fi += fi1 # add file count to gobal file count
# print current folder path with the count of total lines within the folder
if c > 0 and fi1 > 0:
print(fi1, " SUBTOTAL: " + file_path, c, "\n")
# add line count to gobal line count
count += c
else:
# get extension from file path
_, file_extension = os.path.splitext(file_path)
if (file_extension in extenstions):
# sum line count in a file
c = sum(1 for line in open(file_path, encoding="utf8"))
fi += 1 # increment file count
# print current file path with it's count
if c > 0:
print(file_path, c)
# add line count to gobal line count
count += c
return count, fi
# example
if __name__ == "__main__":
# Projects Folders
folders = [
"Backend",
"Admin",
"Frontend",
"ChatModule",
# ...
]
t = 0
tf = 0
out = ""
# traverse each folder mentioned in the list
for folder in folders:
c, fi = getcount(folder)
out += "-" * 80 + "\n" # line seperator
out += folder + "\nTOTAL: %d\nFILES: %d\n" % (c, fi)
t += c
tf += fi
out += "-" * 80 + "\n"
print(out)
print("=" * 80) # seperator
print("Total Lines = ", t)
print("Total Files = ", tf)
print("=" * 80) # seperator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment