w3resource

Python File I/O: Takes a text file as input and returns the number of words of a given text file

Python File I/O: Exercise-18 with Solution

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:

Flowchart: File I/O: Takes a text file as input and returns the number of words of a given text file.

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.



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Split a String:

>>> sentence = 'this is, a python, tutorial, about, idioms.'
>>> sentence.split(', ')
['this is', 'a python', 'tutorial', 'about', 'idioms.']
>>> sentence.split(', ', 2)
['this is', 'a python', 'tutorial, about, idioms.']
>>> sentence.rsplit(', ')
['this is', 'a python', 'tutorial', 'about', 'idioms.']
>>> sentence.rsplit(', ', 2)
['this is, a python, tutorial', 'about', 'idioms.']