您的代码有语法错误;循环后的行for
应该缩进。但实际上解决问题的方法是将其移到循环之外。然后你只需要在循环中放一些别的东西。
import mailbox
for msg in mailbox.mbox('C:\\Users\\hmk\Desktop\\PFE 2019\\ML\\MachineLearningPhishing-master\\MachineLearningPhishing-master\\code\\resources\\mboxfile.mbox'):
pass
# We are now outside the loop, and `msg` contains the last message
print(msg)
当然,更好的解决方法是根本不循环。
messages = mailbox.mbox('C:\\Users\\hmk\Desktop\\PFE 2019\\ML\\MachineLearningPhishing-master\\MachineLearningPhishing-master\\code\\resources\\mboxfile.mbox')
print(messages[messages.keys()[-1]])
以上假设您使用的 Python 版本足够新,可以保持字典按插入顺序排序。如果没有,你可能确实需要循环。
最后,可能不要硬编码绝对文件路径。使您的程序接受文件名参数,以便您可以在任何目录中的任何 mbox 文件上运行它。
import mailbox
import sys
messages = mailbox.mbox(sys.argv[1])
print(messages[messages.keys()[-1]])
像这样称呼它
python3 lastmsg.py C:\Users\hmkDesktop\PFE 2019\ML\MachineLearningPhishing-master\MachineLearningPhishing-master\code\resources\mboxfile.mbox >last
显然,生产脚本应该有一些错误检查和帮助等,但我把这些留作练习。