Count Words in Each Line of Text File Python

By | March 30, 2020

Topic: Count Words in Each Line of Text File Python Program

Count Words in Each Line of Text File

 

# Python program to count 
# number of words in each line of a text  file separately
# 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
i = 0
str1 = ""
print("Contents of file " + file_name + " are:")

# display and count number of  words in each line of text file
for line in file1:
    i+=1
    print(line, end='')
    words_in_line = len(line.split())
    str1 = str1 + "Words in Line No: " + str(i) + " are : " + str(words_in_line)+"\n"
    word_count+=words_in_line
    
print('\n\n ' + str1)    
print('\n\nTotal Number of  words in this file are = ' + str(word_count))

file1.close()

 

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

Words in Line No: 1 are : 5
Words in Line No: 2 are : 4
Words in Line No: 3 are : 4

Total Number of words in this file are = 13

You will also like the following Python File Programs:

How This Python File Program Works?

Count Words in Each Line of Text File

  • First of all the user will input a file name.
  • Open this text file in Read mode.
  • Use for loop to read the text file one line at a time.
  • Use split() method to get words in each line
  • Find the number of words in each line using len() function
  • Display number of words in the current line with line number.
  • Move to the next line.
  • Repeat for all lines in the text file.

Loading

2 thoughts on “Count Words in Each Line of Text File Python

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

  2. Pingback: Python File Copy Program using shutil.filecopy | EasyCodeBook.com

Leave a Reply

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