我设法编写了一段代码(由网络上的多个来源组成,并适应我的需要),它应该执行以下操作:
该代码实际上有效(使用只有 9 封电子邮件的电子邮件文件夹进行测试)。我的问题是运行时间。
该脚本的实际范围是在包含 32700 封电子邮件的文件夹中查找 2539 个值并保存附件。
我已经完成了 2 次运行,如下所示:
我想知道/学习,是否有办法使脚本更快,或者它是否因为写得不好等而变慢。
下面是我的代码:
from pathlib import Path
import win32com.client
import os
from datetime import datetime
import time
import openpyxl
#name of the folder created for output
output_dir = Path.cwd() / "Orders"
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item("Shared Mailbox Name")
inbox = folder.Folders.Item("Inbox")
messages = inbox.Items
wb = openpyxl.load_workbook(r"C:\Users\TEST\Path-to-excel\FolderName\ExcelName.xlsx")
sheet = wb['Sheet1']
names=sheet['A']
for cellObj in names:
ordno = str(cellObj.value)
print(ordno)
for message in messages:
subject = message.Subject
body = message.body
attachments = message.Attachments
if str(subject)[:9] == ordno:
output_dir.mkdir(parents=True, exist_ok=True)
for attachment in attachments:
attachment.SaveAsFile(output_dir / str(attachment))
else:
pass
start = time()
print(f'Time taken to run: {time() - start} seconds')
我需要提一下,我是 Python 的新手,因此欢迎社区提供任何帮助,尤其是在澄清我做错了什么以及为什么做错之后。
我也读过一些类似的问题,但没有任何帮助,或者至少我不知道如何采用这些方法。
谢谢!
在我看来,您的程序的主要问题是当您只需要遍历邮件并检查它们的主题是否在值列表中时,您有两个嵌套循环(一个在值上,一个在邮件上)。
首先,您需要使用以下内容构建价值列表:
ordno_values = [str(cellObj.value) for cellObj in names]
然后,在您的邮件循环中,您只需要将条件调整为:
if str(subject)[:9] in ordno_values:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句