CBSE Class 12 Computer Science Question 140 of 145

File Handling — Question 20

Back to all questions
20
Question

Question 20

Write a function Show_words() in python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them.

Example, if the file contains :

This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.

Then the function should display the output as :

This is a sample file.
The file contains many sentences.

Answer

The file "NOTES.TXT" contains:

This is a sample file.  
The file contains many sentences.   
But need only sentences which have only 5 words.
def Show_words(file_name):
    with open(file_name, 'r') as file:
        for line in file:
            words = line.strip().split()
            if len(words) == 5:
                print(line.strip())


Show_words('NOTES.TXT')
Output
This is a sample file.  
The file contains many sentences.