In this python file program, we will count of a specific word in a file. Let’s consider we have readcontent.txt file with the below content. We will get a count of a specific word in a file with the help of the below-given steps.
# ReadContent.txt
This is Python Programming Language
Its very Python easy to learn to and
Best language for Python beginners
Steps to solve the program
- Open the first file by using open(“readcontent.txt”,”r”).
- Read the data and split it into words using file.read().split().
- Create a variable count and assign its value equal to 0.
- Use for loop to iterate over words.
- If the word is equal to python then add 1 to the count variable.
- Print the respective output.
# Open file with read mode
file = open('readcontext.txt','r')
# Read the data in the file and convert it into words
words = file.read().split()
# Create count variable
count = 0
# Iterate over the words
for word in words:
# Match word
if word == 'Python':
count += 1
# Print output
print("Count of python in the file: ",count)
Output :
Count of Python in the file: 3