Count the Number of Words in a Text File

Write a Python Program to Count the Number of Words in a Text File with practical example.

Problem Description:

The program counts number of words from text file.

Program Logic:

  1. Open file “book.txt” in read mode and store contents of file in file object say fin
  2. Read each line from the file using read() function
  3. Split the line to form a list of words using split() function and store it in variable say l.
  4. Intitially Set the value of count_words variable to zero in which we will store the calculated result.
  5. Use for loop to read list of word stored in variable say l.
  6. Find the length of words in the list and print it.
  7. Close the file using close() function.

Below is implementation code/Source Code:

Here is source code of the Python Program to count the number of words in a text file. The program output is also shown below.

fin = open("book.txt","r")
str = fin.read()
l = str.split()
count_words = 0
for i in l:
    count_words = count_words + 1
print(count_words)
fin.close()


Output:

25

Below is snapshot of executable code:

Below is book.txt file

book.txt text file

You can Also check this too

  1. Python program to get mode and encoding format of file
  2. Python program to search specific data in binary file
  3. Python program to create list of email ids and write list into text file
  4. Python program to select word randomly from text file and store it in another file.
  5. Python program to read all the contents of CSV file and display only specific columns
<