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
- Create an empty list to store the email ids.
- Open the file by using open(“ReadContentEmail.txt”,”r”).
- Read the file using read() and store the data in a variable.
- Now split the data to convert it into words using split() and store the result in a variable.
- Use a for loop to iterate over words.
- Use an if-else statement to check whether the word contains @ in it.
- If yes then add it to the empty list, else continue the loop.
- After for loop is complete print the list of email ids.
- 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']