count_lines

New Programmer

Calculate line count for all .py files in a directory

3 bonuses 8 hints 46 solved 6 reviews

I'd like you to make a function which counts all the lines within .py files in a given directory (recursively).

Your function, count_lines, should accept a directory and should return a single-item dictionary with a "py" key and a value of an object that has files, lines, and non_blank attributes.

Given a directory with the file a.py:

if __name__ == "__main__":
    print('hello world!')

And b.py:

import sys


if __name__ == "__main__":
    if len(sys.argv) > 1:
        print('hello', *sys.argv[1:])
    else:
        print('hello world!')

Passing the current working directory (.) to count_lines should result in a single-item dictionary like this:

>>> for ext, stat in count_lines('.').items():
...     print(ext, stat.files, stat.lines, stat.non_blank)
...
py 2 10 8

There are 2 py files, 10 total lines in these files, and 8 non-blank lines in these files.

This count_lines function should search for py files in the given directory recursively (meaning subdirectories should be searched as well).

Bonus 1


Trey Hunner

Want to solve this one?

Hi, I’m Trey, and I teach Python. Give this one a go, then I’ll show you how I’d solve it.

Sign up and solve it 7 days of All Access, no card needed