I have a project whose lines of code I want to count. Is it possible to count all the lines of code in the file directory containing the project by using Python?
Cloc can be used to count lines in particular file or in multiple files within directory. To use cloc simply type cloc followed by the file or directory which you wish to examine. Now lets run cloc on it. As you can see it counted the number of files, blank lines, comments and lines of code.
The SLOCCount tool may help as well. It will give an accurate source lines of code count for whatever hierarchy you point it at, as well as some additional stats. This will print more than one number when there are many files (because wc will be run multiple times. Also doesn't handle many special file names.
Here's a function I wrote to count all lines of code in a python package and print an informative output. It will count all lines in all .py
import os
def countlines(start, lines=0, header=True, begin_start=None):
if header:
print('{:>10} |{:>10} | {:<20}'.format('ADDED', 'TOTAL', 'FILE'))
print('{:->11}|{:->11}|{:->20}'.format('', '', ''))
for thing in os.listdir(start):
thing = os.path.join(start, thing)
if os.path.isfile(thing):
if thing.endswith('.py'):
with open(thing, 'r') as f:
newlines = f.readlines()
newlines = len(newlines)
lines += newlines
if begin_start is not None:
reldir_of_thing = '.' + thing.replace(begin_start, '')
else:
reldir_of_thing = '.' + thing.replace(start, '')
print('{:>10} |{:>10} | {:<20}'.format(
newlines, lines, reldir_of_thing))
for thing in os.listdir(start):
thing = os.path.join(start, thing)
if os.path.isdir(thing):
lines = countlines(thing, lines, header=False, begin_start=start)
return lines
To use it, just pass the directory you'd like to start in. For example, to count the lines of code in some package foo
:
countlines(r'...\foo')
Which would output something like:
ADDED | TOTAL | FILE
-----------|-----------|--------------------
5 | 5 | .\__init__.py
539 | 578 | .\bar.py
558 | 1136 | .\baz\qux.py
pygount
will display all the files in the folder, each with a count of codes lines (excluding documentation)
https://pypi.org/project/pygount/
pip install pygount
To list the results for the current directory run:
pygount ~/path_to_directory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With