逐行能够执行,用def就会报错某一个变量没有define

写了一个可以批量搜索word内容的代码,逐行复制进去就能够运行,但是使用def就会提示某一个变量没有定义。

def SEARCH(path, keyword):
    os.chdir(path)
    file_list = os.listdir()
    for i in range(len(file_list)):
        exec('file_docx{}=Document(file_list[{}])'.format(i, i))
    for i in range(len(file_list)):
        exec('temp= file_docx{}'.format(i)) #循环读取
        for j in range(len(temp.paragraphs)):  #就是这里报错,提示temp is not defined
            value = temp.paragraphs[j].text.find(keyword)
            if value != -1:
                print(file_list[i] + "\n" + temp.paragraphs[j].text[value:])

实在没法理解为啥会出现这样的问题,找了一圈好像都没有类似的问题出现。

这说明一个道理,没事别用exec

def SEARCH(path, keyword):
    for file in os.listdir(path):
        file_docx = Document(os.path.join(path, file))
        for p, paragraph in enumerate(file_docx.paragraphs):
            result = paragraph.text.find(keyword)
            if result != -1:
                print(f'"{file}" 第{p+1}段 第{result+1}字处查找到匹配的文本 {paragraph.text[result:]}')

img