Some file(file.dat)
#####Start####
sometext
sometext
From: email@address.net
some text
some text
####End#####
1
import re
for line in open('file.dat'):
_mail=re.search(r"\w+@\w+\.\w{2,4}").group()
print(type(_mail))
Out: ‘NoneType’
2
import re
for line in open('file.dat'):
if(re.match(r"From:.*",line)):
_mail=re.search(r"\w+@\w+\.\w{2,4}").group()
print _mail
Out: email@address.net
Explain me, please. Why can’t I use first way?
Your first try will search the mail pattern in each line. The variable _mail will contain, at the end of the loop, the LAST result of re.search (well, the result of re.search on the last line in the file, to be more precise).
So your result will be overwritten.
If you want to use the first way, you have to add:
To end the loop