CBSE Class 12 Computer Science Question 130 of 145

File Handling — Question 10

Back to all questions
10
Question

Question 10

Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and display those words, which are less than 4 characters.

Answer

Let "STORY.TXT" file contain the following text:

Once upon a time, there was a little boy named Jay
He had a dog named Leo
def DISPLAYWORDS(file_name):
    with open(file_name, 'r') as file:
        for line in file:
            words = line.split()
            for word in words:
                if len(word) < 4:
                    print(word)
        for line in file:
            words = line.split()
            for word in words:
                if len(word) < 4:
                    print(word)

DISPLAYWORDS("STORY.TXT")
Output
a
was
a
boy
Jay
He
had
a
dog
Leo