by BehindJava
Write a program to Count the Number of Words in a Text File in Python
In this tutorial we are going to learn about counting the Number of Words in a Text File in Python
Python Program to Count the Number of Words in a Text File
fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Explanation
- User must enter a file name.
- The file is opened using the open() function in the read mode.
- A for loop is used to read through each line in the file.
- Each line is split into a list of words using split().
- The number of words in each line is counted using len() and the count variable is incremented.
- The number of words in the file is printed.