Topic: Count Words in Each Line of Text File Python Program
# 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
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:
words_in_line = len(line.split())
str1 = str1 + "Words in Line No: " + str(i) + " are : " + str(words_in_line)+"\n"
print('\n\n ' + str1)
print('\n\nTotal Number of words in this file are = ' + str(word_count))
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.