Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count Source Lines of Code in Python
# prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints total sloc
import os
cur_path = os.getcwd()
ignore_set = set(["__init__.py", "count_sourcelines.py"])
loclist = []
for pydir, _, pyfiles in os.walk(cur_path):
for pyfile in pyfiles:
if pyfile.endswith(".py") and pyfile not in ignore_set:
totalpath = os.path.join(pydir, pyfile)
loclist.append( ( len(open(totalpath, "r").read().splitlines()),
totalpath.split(cur_path)[1]) )
for linenumbercount, filename in loclist:
print "%05d lines in %s" % (linenumbercount, filename)
print "\nTotal: %s lines (%s)" %(sum([x[0] for x in loclist]), cur_path)
@theelous3

This comment has been minimized.

Copy link

@theelous3 theelous3 commented Jun 17, 2018

ported to py3 and renamed ugly vars

# prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints total sloc

import os
cur_path = os.getcwd()
ignore_set = set(["__init__.py", "count_sourcelines.py"])

loc_list = []

for py_dir, _, py_files in os.walk(cur_path):
    for py_file in py_files:
        if py_file.endswith(".py") and py_file not in ignore_set:
            total_path = os.path.join(py_dir, py_file)
            loc_list.append((len(open(total_path, "r").read().splitlines()),
                               total_path.split(cur_path)[1]))

for line_number_count, filename in loc_list: 
    print("%05d lines in %s" % (line_number_count, filename))

print("\nTotal: %s lines (%s)" %(sum([x[0] for x in loc_list]), cur_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.