Python file program to get all odd and even length words in two lists

In this python file program, we will get all odd and even length words in two lists with the help of the below-given steps.. Let’s consider we have readcontent.txt file with the below content.

				
					Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the data and split it into words using file.read().split().
  3. Create two empty lists even and odd.
  4. Use a for loop to iterate over the words.
  5. If the length of the word is even then add it to the even list, else add it to the odd list.
  6. Use an if-else statement for this purpose.
  7. Print the output.
				
					# Open the file
file = open('readcontent.txt')
# Convert data into words
words = file.read().split()
# Create empty lists
even = []
odd = []
# Iterate over words
for word in words:
# Check for odd,even words
# Add them to corresponding list
    if len(word)%2==0:
        even.append(word)
    else:
        odd.append(word)
# Print output
print("Words having even length: ",even)
print("Words having odd length: ",odd)
				
			

Output :

Words having even length:
[‘This’, ‘is’, ‘India.’, ‘This’, ‘is’, ‘America.’, ‘This’, ‘is’, ‘This’, ‘is’, ‘Australia.’, ‘This’, ‘is’, ‘This’, ‘is’, ‘Korea.’, ‘This’, ‘is’, ‘Germany.’, ‘This’, ‘is’, ‘China.’]

Words having odd length:
[‘Line1’, ‘:’, ‘Line2’, ‘:’, ‘Line3’, ‘:’, ‘Canada.’, ‘Line4’, ‘:’, ‘Line5’, ‘:’, ‘Africa.’, ‘Line6’, ‘:’, ‘Line7’, ‘:’, ‘Line8’, ‘:’]

 

 

generate text files with all alphabets.  e.g. A.txt , B.txt, C.txt….. Z.txt

get all mobile numbers from a file.

Leave a Comment