A line count tells you how many lines a text file contains. In Python, it can be one result of a small file-analysis program that also counts words and characters. The same approach works for a source-code file. section 8.12
Count while reading
Start with `line_count = 0`, then use `with open('word_count.tst') as infile:` followed by `for line in infile: line_count += 1`. The four-line sample produces a line count of 4. Counting as you read avoids keeping the whole file in a list. section 8.12 section 8.13.2 section 11.5.2
For a file already read with `readlines()`, `len(lines)` gives its line count. Reading the entire file and using `split('\n')` also produces pieces to count, but it removes the newline separators. In the sample, that choice makes the accompanying character count 186 rather than 189. Prefer the line-by-line approach when the file might be large. section 8.13.2 section 11.5.2
For a command-line counter, an `argparse` `-l` or `--lines` option can select the line count. With no count options selected, the program can display its standard set of line, word, and character counts. section 11.5.2
""" Reads a file and returns the number of lines, words,
and characters - similar to the UNIX wc utility
"""
# initialize counts
line_count = 0 #1
word_count = 0 #1
char_count = 0 #1
# open the file
with open('word_count.tst') as infile:
for line in infile: #2
line_count += 1
char_count += len(line)
word_count += len(line.split())
# print the answers using the format() method
print("File has {0} lines, {1} words, {2} characters".format(line_count,
word_count, char_count))
This short implementation increments the line count during file iteration and counts words and characters in the same pass. section 8.13.2
