How to Count the Number of the Words in a File with Python


In this example we will show how to get the file name and count the number of words in the file with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter the name of the file with .txt extension: ")
count = 0
with open(fileName, 'r') as file:
    for line in file:
        wordList = line.split()
        count += len(wordList)
print("The number of words is: ", count)
Content of test1.txt: 
Python is an easy to learn
powerful programming language

Output:

Enter the name of the file with .txt extension: test1.txt
The number of words is:  9
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments