Python中for j in range(0, len(files)): NameError: name 'files' is not defined

代码:

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

报错:

  File "SendMail.py", line 11
    print("错误!!! 收件人名称和附件名称不一致!!!")
    ^
IndentationError: expected an indented block

Process finished with exit code 1

请问改如何解决呢?

代码格式移位导致程序错误,按下面修改即可

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

你的第二个for应该包含在第一个for里

files是在第一行的for中定义的,作用范围只能在第一个for循环内
你在第二个for循环内部访问files,自然不认识了。是不是4-8行全部要向内缩进一层,或者将files变量定义到第一个for循环外

主要是代码缩进不对, 缩进是python语法中很重要的一部分,python不像C或java有花括号区分代码的层级关系,所以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


如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮