[Solved] How to count all lines, words, and characters in a file


I would reccomend using with (docs) whenever you do file I/O in python. Also, iterate over each line instead of using inFile.read(). If you have a large file, your machines memory will thank you.

def stats(inF):

    num_lines = 0
    num_words = 0
    num_chars = 0

    with open(inF, 'r') as input_file:
        for line in input_file:
            num_lines += 1
            line_words = line.split()
            num_words += len(line_words)
            for word in line_words:
                num_chars += len(word)

    print  'line count: %i, word count: %i, character count: %i' % (num_lines, num_words, num_chars)


stats('test.txt')

solved How to count all lines, words, and characters in a file