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
- Open the first file by using open(“readcontent.txt”).
- 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.
- After each iteration add 1 to the count variable.
- 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.