In this python file program, we will display words from a file that has less than 5 characters with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.
#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.
Steps to solve the program
- Open the file by using open(“readcontent.txt”).
- Where the file name is the name of the file.
- Read the data and split it into words using file.read().split().
- Use a for loop to iterate over the words.
- If the length of the word is less than 5 then print that word.
- Use an if statement for this purpose.
# Open the file
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Iterate over words
for word in words:
# Check for words having length less than 5
if len(word)<5:
# Print output
print(word,end=" ")
Output:
My name is I’m 20 old. I’m at I’m from