调整脚本以从文本文件中读取

时间:2011-11-29 16:54:31

标签: python csv

我有以下脚本需要适应从文件中读取,特别是我需要提取“域”和“预期响应”。目前它们是在代码中手动编写的,因为我不够熟练,不能更有效地重构它。

#!/usr/bin/python
import dns.resolver
from smtplib import SMTP
import datetime

debuglevel = 0

domain = 'exampledomain.co.uk'
expected_responses = ['example.co.uk.', 'example2.co.uk.']
for x in dns.resolver.query(domain, 'MX'):
        if x.to_text().split()[1] not in expected_responses:
                print "Unexpected MX record found!"
                smtp = SMTP()
                smtp.set_debuglevel(debuglevel)
                smtp.connect('localhost', 25)

                from_addr = "MX ERROR <MXERROR@example.net>"
                to_addr = "example@example.com"

                subj = "MX ERROR"
                date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

                message_text = "Dearest colleagues\nSomething appears to be wrong with the MX records for example.co.uk\n\nDON'T PANIC!\n"

                msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text )


                smtp.sendmail(from_addr, to_addr, msg)
                smtp.quit()
        else:
                print x.to_text().split()[1] + " example.uk MX records OK!"

我的第一个想法是使用.txt文件,但我无法弄清楚如何使用我的python知识区分同一文件中的域和expected_responses。我有一个关于import csv函数的搜索和阅读,这似乎是最好的选择,但我没有任何使用它的经验。

是否有人能够向我提供如何将导入csv应用于我的代码的示例?

此致

克里斯

1 个答案:

答案 0 :(得分:1)

http://docs.python.org/library/configparser.html

这可能更符合您的需求。使用* .ini文件似乎是配置文件的一种非常标准的做法。

相关问题