Count Lines of Code

Introduction

Sometimes it is interesting (and useful) to count the various types of lines in a Python file.

Project #1

Write a interactive program to count the line in a Python file.

Program structure...

  1. ask the user for the name of a Python file
  2. If an empty string, exit
  3. if the file name does not end in '.py'
    • display error message
    • loop
  4. process each line in the file
    • increment the total line count
    • remove all spaces (blanks) at the beginning and end of each line
    • if the line is blank, increment the blank line count
    • if not blank, increment the code count
    • if the line starts with '#', increment the comment count
    • if the line starts with 'def', increment the function count
  5. after processing the file display the counts
  6. loop

Also display the percentage of the total for each type of line. (Don't go crazy, round to the percent.)

Use regular expressions?

Project #2

Expand Project #1. Find all of the '.py' files in a folder. Collect and display the total counts and percentages for all '.py' files.

Project #3

If you are working on a project that uses several programming languages, create a code counting program that distinguishes between file types. Remember a comment in one language may not be a comment in another. (Change the counting rules for each language.)

Note: Different file types have have different extensions (suffixes)

Question

Does your operating system distinguish between '.py' and '.PY' files?
Does your Python interpreter distinguish between '.py' and '.PY' files?