Python文件在写入后仍然为空

2024-04-27 01:03:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图直接从MYSQLDB表和tldextract中读取URL,以便从URL中获取域,并找到域的SPF(Sender Policy Framework)记录。你知道吗

当我试图写我扫描的每个域的SPF记录时,我的Ouput_SPF_Records.txt不包含我写的任何记录。你知道吗

对这个问题不确定,有什么建议吗?你知道吗

import sys
import socket
import dns.resolver
import re
import MySQLdb
import tldextract
from django.utils.encoding import smart_str, smart_unicode

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','')

db=MySQLdb.connect("x.x.x.x","username","password","db_table")
cursor=db.cursor()
cursor.execute("SELECT application_id,url FROM 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') as out:
        domain=smart_str(d)
        #print domain
        with open('Ouput_SPF_Records.txt','w') as 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()

Tags: importtxtidappdatasmartdomain记录
3条回答

你的问题是你打开文件很多次,每次都是通过循环。使用w模式,从一开始就删除内容和写入。你知道吗

要么在循环之前打开一次文件,要么以附加模式a打开,这样就不会删除以前写入的数据。你知道吗

尝试用append模式而不是w模式打开文件。w模式在每次迭代中覆盖文件。示例-

with open('Ouput_SPF_Records.txt','a') as g:

最可能的情况是,上次以写模式打开文件时,您没有在中写入任何内容,因为您正在捕获并忽略所有异常,这会导致空文件。你知道吗

另外,如果知道预期的错误,应该使用except <Error>:而不是except Exception:。示例-

try:   
    full_spf=getspf(domains.strip())+"\n"
    spf_rec=app_id+","+full_spf
    print spf_rec
except <Error you want to catch>:
    pass

您可以使用:

import pdb;pdb.set_trace()

调试代码并尝试找出问题所在。 还要注意: 1你不应该只在try/except块中写“pass”。处理例外情况

2。你知道吗

 with open('Ouput_SPF_Records.txt','w') as g:

它将自动关闭文件,因此无需显式执行:g.close()。你知道吗

相关问题 更多 >