Python Count Words in Text File

By | March 30, 2020

Topic: Count Words in Text File Python Program

# Python program to count 
# number of words in a text  file
# Input filename, open it in 
# read mode. display its cntents 
# count and display number of  words
# www.EasyCodeBook.com

file_name = input("Enter file name:")

file1 = open(file_name, "r")

word_count = 0
print("Contents of file " + file_name + " are:")

# display and count number of  words
for line in file1:
    print(line, end='')
    words_in_line = len(line.split())
    word_count+=words_in_line

print('\n\nTotal Number of  words in this file are = ' + str(word_count))

file1.close()

Python Count Words in Text File

How this Program works?

  • First of all we will show a message to the to enter the name of the file.
  • The user will input a valid file name.
  • We use input() function of Python for the above mentioned task.
  • open() function will be used to open the given file in read mode, since we supply two arguments, the file name and an opening mode “r”.
  • Set a word_count variable to zero.
  • We will use a for loop to read and print contents of the file:
  • We will read the given file line by line.
  • Each line is split into words
  • The words of that line are counted and added to the total word count of the file.
  • We will show the total number of words in the text file.

 

Note: This is to be noted that a file with name “example.txt” must be present at d: drive. As an example we create a file with name example.txt on D: drive with the following contents, as shown in the above image:

this is example text file
this is line 2
this is last line

Output

Enter file name:d://example.txt
Contents of file d://example.txt are:
this is example text file
this is line 2
this is last line

Total Number of words in this file are = 13

You will also like the following Python File Programs:

 

Loading

2 thoughts on “Python Count Words in Text File

  1. Pingback: Count Words in Each Line of Text File Python | EasyCodeBook.com

  2. Pingback: Find Occurrences of Each Word in Text File Python Program | EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *