Write a python program to count the number of words in a file :

This tutorial is to count the number of words of a file using python. We will pass the file name to the program and it will scan the file and print out the count.
1. Open the file in read only mode as ‘open(filename,’r’)’
2. Scan each line using a ‘for’ loop
3. split the line using ‘split()’. It will return a list of words. Get the count of all words using ‘len()’ method.
4. Add this words count to the final ‘result’ value.
5. After all lines are scanned, print out the result .

Program :

word_count = 0

file_name = "D//in.txt"

with open(file_name,'r') as file:
	for line in file:
		word_count += len(line.split())

print ("number of words : ",word_count)

Sample output:

The quick brown fox 
jumps over the 
lazy dog

For a file containing these words, the output will be 9.

Categories: python

Leave a Reply

Your email address will not be published. Required fields are marked *