我是Python的新手,我创建了一些简单的Python代码(下面)来打印(或返回)主体,主题和.eml文件的电子邮件地址。这很好用。但是,如何将此代码应用于.eml文件的文件夹?
import email
fp = open('C:\emlfiles\TEST_00000.eml')
msg = email.message_from_file(fp)
subject = msg.get('subject')
subject = str(subject)
fromAdd = msg.get('from')
fromAdd = str(fromAdd)
payload = msg.get_payload()
if type(payload) == type(list()) :
payload = payload[0]
if type(payload) != type('') :
payload = str(payload)
print subhec + fromAdd + payload
答案 0 :(得分:2)
看看os.walk
,它会做你想要的。
答案 1 :(得分:1)
使用os.listdir
:
import email
infolder = "C:\\emlfiles\\"
for infile in os.listdir(infolder):
fp = open(os.path.join(infolder, infile))
msg = email.message_from_file(fp)
# etc
也许更好的方法是将该代码包装在一个函数中然后调用它:
def process_email(infile):
fp = open(infile)
msg = email.message_from_file(fp)
subject = msg.get('subject')
infolder = "C:\\emlfiles\\"
for infile in os.listdir(infolder):
process_email(os.path.join(infolder, infile))