Python File Remains Empty After Writing to it Issue -
i trying read url directly mysqldb
table , tldextract
domain url , find spf(sender policy framework) record domain.
when i'm trying write spf records of each , every domain scan,my ouput_spf_records.txt
not contain records write.
not sure issue,any suggestions please ?
import sys import socket import dns.resolver import re import mysqldb import tldextract django.utils.encoding import smart_str, smart_unicode def getspf (domain): answers = dns.resolver.query(domain, 'txt') rdata in answers: txt_string in rdata.strings: if txt_string.startswith('v=spf1'): return txt_string.replace('v=spf1','') db=mysqldb.connect("x.x.x.x","username","password","db_table") cursor=db.cursor() cursor.execute("select application_id,url app_info.app_urls") data=cursor.fetchall() x=0 while x<len(data): c=tldextract.extract(data[x][1]) #print c app_id=data[x][0] #print app_id d=str(app_id)+','+c[1]+'.'+c[2] #with open('spfout.csv','a') out: domain=smart_str(d) #print domain open('ouput_spf_records.txt','w') g: full_spf="" spf_rec="" y=domain.split(',') #print "y===",y,y[0],y[1] app_id=y[0] domains=y[1] try: full_spf=getspf(domains.strip())+"\n" spf_rec=app_id+","+full_spf print spf_rec except exception: pass g.write(spf_rec) x=x+1 g.close()
try openning file append mode, instead of w
mode. w
mode overwrites file in each iteration. example -
with open('ouput_spf_records.txt','a') g:
most probably, last time open file in write mode, not write in since, catching , ignoring exceptions , causes empty file.
also, if know error expecting, should use except <error>:
instead of except exception:
. example -
try: full_spf=getspf(domains.strip())+"\n" spf_rec=app_id+","+full_spf print spf_rec except <error want catch>: pass
Comments
Post a Comment