I am trying to create a script that takes a file as input, looks up all the email addresses, and writes them to a designated file.
based on other similar questions, i have ended up with this:
import re
Input = open("inputdata.txt", "r")
regex = re.compile("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")
Logfile = "Result.txt"
for line in Input:
query = regex.findall(line)
for line in query:
print >>Logfile, query
what am i doing wrong? this outputs nothing. i am guessing the main problem is "for line in query:", which i have tried changing without any luck.
Cheers!
Edit: i have changed the script as suggested below, with "print (query)" instead. i still do not get any output. current script is:
import re
Input = open("Inputdata.txt", "r")
regex = re.compile("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")
# logfile = "Result.txt"
for line in Input:
query = regex.findall(line)
for line in query:
with open("Result.txt", "a") as logfile:
logfile.write(line)
It outputs nothing, and tells me: " NameError: name "logfile" not defined". what causes this, and is this the reason there is no output?
Logfiletologfile(i.e. lower case) to comply to coding conventions. Also, you do not have to open the file anew in each iteration. Move thewith ...line on top of your loop.