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:
- Open file “book.txt” in read mode and store contents of file in file object say fin
- Read each line from the file using read() function
- Split the line to form a list of words using split() function and store it in variable say l.
- Intitially Set the value of count_words variable to zero in which we will store the calculated result.
- Use for loop to read list of word stored in variable say l.
- Find the length of words in the list and print it.
- 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


You can Also check this too
- Python program to get mode and encoding format of file
- Python program to search specific data in binary file
- Python program to create list of email ids and write list into text file
- Python program to select word randomly from text file and store it in another file.
- Python program to read all the contents of CSV file and display only specific columns
<