Reputation: 1220
I'm trying to get the SPF records
of a domains
and the domains are read from a file.When i am trying to get the spf contents and write it to a file and the code gives me the results of last domain got from input file.
Example `Input_Domains.txt`
blah.com
box.com
marketo.com
The output,I get is only for the marketo.com
#!/usr/bin/python
import sys
import socket
import dns.resolver
import re
def getspf (domain):
answers = dns.resolver.query(domain, 'TXT')
for rdata in answers:
for txt_string in rdata.strings:
if txt_string.startswith('v=spf1'):
return txt_string.replace('v=spf1','')
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf=getspf(line.strip())
my_file=open("out_spf.txt","w")
my_file.write(full_spf)
my_file.close()
How can i solve this by writing all the spf contents of domains which i got it to file,Any suggestions please ?
Upvotes: 0
Views: 45
Reputation: 10119
Try using a generator expression inside your with
block, instead of a regular for
loop:
full_spf = '\n'.join(getspf(line.strip()) for line in f)
This will grab all the lines at once, do your custom getspf
operations to them, and then join them with newlines between.
The advantage to doing it this way is that conceptually you're doing a single transformation over the data. There's nothing inherently "loopy" about taking a block of data and processing it line-by-line, since it could be done in any order, all lines are independent. By doing it with a generator expression you are expressing your algorithm as a single transformation-and-assignment operation.
Edit: Small oversight, since join
needs a list of strings, you'll have to return at least an empty string in every case from your getspf
function, rather than defaulting to None
when you don't return anything.
Upvotes: 2
Reputation: 8335
It is because you are rewriting full_spf
all the time so only last value is stored
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf=getspf(line.strip())
Modification:
with open('Input_Domains.txt','r') as f:
full_spf=""
for line in f:
full_spf+=getspf(line.strip())+"\n"
Upvotes: 3