检查硬反弹电子邮件时python上的条件

检查硬反弹电子邮件时python上的条件,python,smtp,Python,Smtp,我编写Python脚本来验证硬反弹 from validate_email import validate_email with open("test.txt") as fp: line = fp.readline() cnt = 1 while line: line = fp.readline() print ('this email :' + str(line) +'status : ' + str((validate_email

我编写Python脚本来验证硬反弹

from validate_email import validate_email

with open("test.txt") as fp:  
    line = fp.readline()
    cnt = 1
    while line:
        line = fp.readline()
        print ('this email :' + str(line) +'status : ' + str((validate_email(line,verify=True))))
        stt=str(validate_email(line,verify=True))
        email=str(line)
        print ("-----------------") 
        cnt += 1
        if stt == "True":
            file=open("clean.txt",'w+')
            file.write(email)
        if stt == "None":
            file=open("checkagain.txt",'w+')
            file.write(email)
        if stt == "False":
            file=open("bounces.txt",'w+')
            file.write(email) 

如果条件为False,则创建文件,但内部没有电子邮件,即使我确定我有反弹电子邮件

您需要关闭文件以反映文件中的更改,请放入:

file.close()
最后

您应该改为使用:

with open('bounces.txt', 'a') as file:
# your file operations

这样,您就不必关闭文件

您的脚本包含许多错误

  • 每个输入行都包含一个尾随换行符
  • 打开同一个文件进行多次写入效率极低。未能关闭文件是导致文件最终为空的原因。在不关闭的情况下重新打开可能会丢弃您在某些平台上编写的内容
  • 一些操作重复进行,一些只是导致效率低下,另一些则是彻头彻尾的错误
这里是一个重构,包含对更改的内联注释

from validate_email import validate_email

# Open output files just once, too
with open("test.txt") as fp, \
        open('clean.txt', 'w') as clean, \
        open('checkagain.txt', 'w') as check, \
        open('bounces.txt', 'w') as bounces:
    # Enumerate to keep track of line number
    for i, line in enumerate(fp, 1):
        # Remove trailing newline
        email = line.rstrip()
        # Only validate once; don't coerce to string
        stt = validate_email(email, verify=True)
        # No need for str()
        print ('this email:' + email +'status: ' + stt)
        # Really tempted to remove this, too...
        print ("-----------------")
       # Don't compare to string
        if stt == True:
            clean.write(line)
       elif stt == None:
            check.write(line)
        elif stt == False:
            bounces.write(line) 

您没有使用行号进行任何操作,但我保留了行号以显示通常的操作方式。

是否关闭该文件?您应该使用带有open('bounces.txt','a')的
作为文件:
另外:调用
fp.readline()
两次意味着您每第二行跳过一次。输入是什么?每行只有一个电子邮件地址?