NameError:使用Python下载Excel附件时未定义名称'att'

问题描述 投票:-1回答:1

当使用Python 2.7从Outlook自动下载Excel附件时,我收到一条错误消息:NameError:name'att'未定义。奇怪的是,代码工作正常,直到今天。

我尝试移动:att.SaveAsFile到内部循环。

# Imports arcpy library (Python for ArcGIS) and other libraries required
import arcpy
import os
import sys
import datetime
import win32com.client
from win32com.client import Dispatch
import csv
import pandas as pd
import numpy as np
from tempfile import NamedTemporaryFile
import logging
#import string

"""
Part I:  Downloads Excel Spreadsheet (Named Test) from Outlook
"""
# Reference: https://stackoverflow.com/questions/22399835/how-to-save-attachment-from-outlook-using-win32com-client-in-python
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
#messages= msg.Attachments
val_date = datetime.date.today()

sub_today = 'Test ' + date_string
att_today = 'Test ' + date_string+'.xlsx'

# Loop through messages and stop at message with today's subject and attachment.
for msg in all_inbox:
    if msg.Subject:
        new=msg.Subject
        if new.find('Test') !=-1 & new.find(date_string) !=-1:
            #print("Step 1")
            break

for att in msg.Attachments:
    if att.FileName:
        #print("Step 2")
        break

# Change Directory and Save Attachment  
os.chdir('My Directory')
att.SaveAsFile(os.getcwd()+'\\'+att_today)
logging.info('Finished Attachment Download')
python outlook download attachment
1个回答
1
投票

如果附件列表为空,或者没有设置att.FileName,则会出现上述错误。有一个很好的python技巧可以避免它:你可以使用else作为for循环。 else中的代码将被执行,如果你迭代收集并且从未命中break

这是一个例子:

log = logging.getLogger(__name__)

for att in msg.Attachments:
    if att.FileName:
        break
else:
    log.error("file is not found")
    att = None

if att:
    att.SaveAsFile(att_today)
    log.info('Finished Attachment Download')

只有1个附件吗?

© www.soinside.com 2019 - 2024. All rights reserved.