Python File I/O: Takes a text file as input and returns the number of words of a given text file
18. Count Words in File
Write a Python program that takes a text file as input and returns the number of words of a given text file.
Note: Some words can be separated by a comma with no space.
words.txt: Write a Python program that accept some words and count the number of distinct words. Print the number of distinct words and number of occurrences for each distinct word according to their appearance.
Sample Solution:
Python Code:
def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(",", " ")
return len(data.split(" "))
print(count_words("words.txt"))
Sample Output:
33
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to count the total number of words in a text file, treating commas without spaces as word separators.
- Write a Python script to read a file and count words while normalizing punctuation and whitespace.
- Write a Python program to compute the word count in a file and output the result along with the file name.
- Write a Python function to count words in a file, considering various delimiters (commas, spaces, semicolons) and print the total count.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to remove newline characters from a file.
Next: Write a Python program to extract characters from various text files and puts them into a list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.