How can I extract all mail ids from a text file in Python?

python

#1

I have mail ids available in a txt file with other details also. Now I want to extract the mail Ids only. Please help me to perform this. Below is the sample data of the txt file.

John@gmail.com, 34567 , John, Abhay@Yahoo.com, 45342,Abhay, Deepak@gmail.com, 56342, Deepak, Sahil@rediffmail.com,32123, Sahil, Solomon@gmail.com, 43214,Solomon, Javed@yahoo.co.in, 76543, Jave

Thx,
Imran


#2

You can extract these with regular expressions. Have a look at the re package.


#3

@Imran,

Below is the code of regular expression to solve this.

Code

  f=open('Email.txt','r+')
  import re
  r=re.findall("[\w]+@[\w.]+",f.read())
  print r
  f.close

Output

['John@gmail.com', 'Abhay@Yahoo.com', 'Deepak@gmail.com', 'Sahil@rediffmail.com', 'Solomon@gmail.com', 'Javed@yahoo.co.in']

You can read more about regular expression here. https://docs.python.org/2/howto/regex.html.

Hope this helps!

Regards,
Sunil