Python file program to count all the words from a file

In this python file program, we will count all the words from a file. Let’s consider we have readcontent.txt file with the below content. We will count all the words from a file with the help of the below-given steps.

				
					# ReadContent.txt
This is Python
This is Java
Python is good language Poetry' );
				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the data and split it into words using file.read().split().
  3. Create a variable count and assign its value equal to 0.
  4. Use for loop to iterate over words.
  5. After each iteration add 1 to the count variable.
  6. Print the total number of words in the file.
				
					# Open the file
file = open('readcontent.txt')
# Convert data to words
words = file.read().split()
# Create a count variable
count = 0
# Iterate over words
for word in words:
# Add 1 to the count variable for each word
    count += 1
# Print output
print("Count of words in the file: ",count)
				
			

Output: 

Count of words in the file: 10

 

 

copy the file’s contents to another file after converting it to uppercase.

Leave a Comment