python 缩进问题解答

代码:

for root, dirs, files in os.walk('groupmailroger'):
    print(files) #当前路径下所有非目录子文件
    print(root)
    count = 0
    for i in range(0, len(receiversAddressName)):
        for j in range(0, len(files)):
            if (bool(re.search(str(receiversAddressName[i]), str(files[j]))) == True):
                count = count + 1
    SendFlag = False
    if count != len(receiversAddressName):
        print("错误!!! 收件人名称和附件名称不一致!!!")
    else:
        SendFlag = True
class send_email():
    def outlook(self):
        for i in range(0, len(receiversAddressMail)):
            mail_path_content = os.path.join('groupmailroger', 'Content.txt')
            mail_path_attachment = os.path.join('groupmailroger', receiversAddressName[i] + '.xlsx')
            olook = win32.Dispatch("outlook.Application")  # 固定写法
            mail = olook.CreateItem(0)  # 固定写法
            mail.To = receiversAddressMail[i]  # 收件人邮箱
            mail.CC = receiver_cc_AddressMail[i] # 需要CC的邮箱
            mail.Subject = 'SP签约达成及季返数据_Sep'  # 邮件主题
            mail.Attachments.Add(mail_path_attachment, 1, 1, receiversAddressName[i]) # 添加附件
            read = open(mail_path_content, encoding='utf-8')  # 邮件正文
            content = read.read()  # 读取测试报告文件中的内容
            read.close()
            mail.Body = content  # 将从报告中读取的内容,作为邮件正文中的内容
            mail.Send()  # 发送
    if __name__ == '__main__':
        if SendFlag == True:
            send_email().outlook()
            print("send email ok!!!!!!!!!!")
        else:
            print("send email Fail!!!!!!!!!!")

报错:

Traceback (most recent call last):
  File "C:\Users\SESA618240\OneDrive - Schneider Electric\桌面\groupmailroger\SendMail.py", line 14, in <module>
    class send_email():
  File "C:\Users\SESA618240\OneDrive - Schneider Electric\桌面\groupmailroger\SendMail.py", line 31, in send_email
    if SendFlag == True:
NameError: name 'SendFlag' is not defined

if缩进位置错误,按图中修改if语句位置即可

if __name__ == '__main__':
    if SendFlag == True:
        send_email().outlook()
        print("send email ok!!!!!!!!!!")
    else:
        print("send email Fail!!!!!!!!!!")

img

刚开始的SendFlag = False应该放for循环外,最后的if开始到结束每行都删去一个缩进

img

跟缩进没关系
你的SendFlag是在class外面定义的,还不是全局变量,是在另一个代码块里面定义的
那class里面当然无法访问了