Python By Example

Count the number of words in a file

by Jiffin Joachim Gomez on 24th February 2017

This is a simple Python script to count the number of words in file.

The program imports counter class from Python library collections and uses counter class to count the number words in a file. This program uses various built in functions:

This program prompts the user to input a file name. The file is opened in readonly mode and using the counter class counts the words in a file.

# Python program to count the number of words in file

# importing counter class from python library collections.
from collections import Counter

fname = str(input("Input a file name : "))
c = Counter()
# Open file in read only mode
with open(fname, 'r') as f:
    for ln in f:
        c.update(ln.split())

total = sum(c.values())
total += 1
print("The file", fname, "contains", total, "words.")

Program Output

Input a file name : c:\myInputFile.txt
The file c:\myInputFile.txt contains 28 words.
>>> 

Post a comment

Comments

Nothing yet..be the first to share wisdom.