A character count reports the number of characters in a text file. A small Python program can calculate it alongside line and word counts, much like the UNIX wc utility. section 8.12
""" 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))
The line-by-line version adds len(line) to a running total. Counting each line as read keeps its newline in the count and avoids loading the whole file at once. section 8.13.2
Newlines change the answer
For the four-line sample file, splitting the entire file with split("\n") and summing the lengths of the resulting strings reports 186 characters. The three separators have been discarded; counting the original lines reports 189. section 8.12 section 8.13.2
Another compact approach is sum(len(line) for line in infile.readlines()), but readlines() holds the file's lines in memory. For files of unknown size, iterate over the file instead. In a command-line version, a -c option can request the character count; with no options, line, word, and character counts can be displayed together. section 8.13.2 section 11.5.2
