Program to get all the email ids from a text file

In this python file program, we will get all the email ids from a text file. Let’s consider we have ReadContentEmail.txt file with the below content.
We will get the email ids from the file with the help of the below-given steps.

				
					Line1 : This is India.
Line2 : This is America.
Line3 : This test1@gmail.com first email.
Line4 : This is Australia.
Line5 : This test2@gmail.com first email.
Line6 : This is Korea.
Line7 : This test3@gmail.com first email.
Line8 : This is China.
				
			
Steps to solve the program
  1. Create an empty list to store the email ids.
  2. Open the file by using open(“ReadContentEmail.txt”,”r”).
  3. Read the file using read() and store the data in a variable.
  4. Now split the data to convert it into words using split() and store the result in a variable.
  5. Use a for loop to iterate over words.
  6. Use an if-else statement to check whether the word contains in it.
  7. If yes then add it to the empty list, else continue the loop.
  8. After for loop is complete print the list of email ids.
  9. Close the file.
				
					# Create an empty list
email_list = []
# Open the file in reading mods
file = open("ReadContentEmail.txt", "r")
# Read the data in the file
file_data = file.read()
# Convert the data into words
word_list = file_data.split(" ")
# Iterate over the words
for word in word_list:
# Check for @ in the word
    if "@" in word:
    # Add word to the empty list
        email_list.append(word)
    else:
        continue
# Print output
print(email_list)
# Close the file
file.close()
				
			

Output : 

				
					['test1@gmail.com', 'test2@gmail.com', 'test3@gmail.com']
				
			

 

 

get the file’s first three and last three lines.

get a specific line from the file.

Leave a Comment