【发布时间】:2021-08-10 22:04:39
【问题描述】:
我正在运行下面的代码,几天来它就像一个魅力,现在我面临以下错误消息:“列表索引超出范围”与:
for i in range(item_count, 0, -1):
message = out_iter_folder.Items[i]
这段代码已经完美运行了数周,我可以通过将计算出的 item_count 值替换为相同的值 -1 来修复它,但不确定它为什么会工作并停止工作?
非常感谢:)!
import win32com.client
EMAIL_ACCOUNT = 'Enter your email address' # e.g. 'good.employee@importantcompany.com'
ITER_FOLDER = 'Enter the Outlook folder name which emails you would like to iterate through' # e.g.
'IterationFolder'
MOVE_TO_FOLDER = 'Enter the Outlook folder name where you move the processed emails' # e.g
'ProcessedFolder'
SAVE_AS_PATH = 'Enter the path where to dowload attachments' # e.g.r'C:\DownloadedCSV'
EMAIL_SUBJ_SEARCH_STRING = 'Enter the sub-string to search in the email subject' # e.g. 'Email to
download'
def find_download_csv_in_outlook():
out_app = win32com.client.gencache.EnsureDispatch("Outlook.Application")
out_namespace = out_app.GetNamespace("MAPI")
out_iter_folder = out_namespace.Folders[EMAIL_ACCOUNT].Folders[ITER_FOLDER]
out_move_to_folder = out_namespace.Folders[EMAIL_ACCOUNT].Folders[MOVE_TO_FOLDER]
char_length_of_search_substring = len(EMAIL_SUBJ_SEARCH_STRING)
# Count all items in the sub-folder
item_count = out_iter_folder.Items.Count
if out_iter_folder.Items.Count > 0:
for i in range(item_count, 0, -1):
message = out_iter_folder.Items[i]
# Find only mail items and report, note, meeting etc items
if '_MailItem' in str(type(message)):
print(type(message))
if message.Subject[0:char_length_of_search_substring] == EMAIL_SUBJ_SEARCH_STRING \
and message.Attachments.Count > 0:
for attachment in message.Attachments:
if attachment.FileName[-3:] == 'csv':
attachment.SaveAsFile(SAVE_AS_PATH + '\\' + attachment.FileName)
message.Move(out_move_to_folder)
else:
print("No items found in: {}".format(ITER_FOLDER))
if __name__ == '__main__':
find_download_csv_in_outlook()
【问题讨论】:
-
Python 列表索引是从零开始的。长度列表
4具有索引0、1、2和3。您需要从len(list) - 1迭代到零(包括两者),因此您需要执行range(len(list) - 1, -1, -1)。看到这个类似的最近问题:stackoverflow.com/q/67593572/843953 -
你确定它有效吗?
range(5, 0, -1)开始于5并结束于1并且很可能out_iter_folder.Items[i]在第一次迭代时超出范围,因为列表是0-based并且期望索引从4开始并以 @ 结束987654337@. -
我怀疑您发布的代码工作正常,然后莫名其妙地停止工作。您一定是在某些编辑中引入了错误。
标签: python python-3.x list loops