首页 > 解决方案 > 文件迭代'NoneType'对象在for循环中不可迭代

问题描述

我查看了有关此 TypeError 的其他帖子,但他们并没有帮助我弄清楚这一点。发生错误的地方是我试图循环浏览从土工布函数返回的文件列表,然后在它们中搜索用户的输入。但由于 NoneType,它似乎无法进入“for I in files:”循环。是什么导致文件列表为无类型?

# Program to accept user input and search all .txt files for said input

import re, sys, pprint, os


def getTxtFiles():
    # Create a list of all the .txt files to be searched
    files = []
    for i in os.listdir(os.path.expanduser('~/Documents')):
        if i.endswith('.txt'):
            files.append(i)

def searchFiles(files):
    ''' Asks the user for input, searchs the txt files passed,
     stores the results into a list'''
    results = []
    searchForRegex = re.compile(input('What would you like to search all the text files for?'))
    for i in files:
        with open(i) as text:
            found = searchForRegex.findall(text)
            results.append(found)


txtFiles = getTxtFiles()
print(searchFiles(txtFiles))

Traceback (most recent call last):
  File "searchAll.py", line 26, in <module>
    print(searchFiles(txtFiles))
  File "searchAll.py", line 19, in searchFiles
    for i in files:
TypeError: 'NoneType' object is not iterable

标签: pythonregexfor-loopnonetype

解决方案


您的 getTextFiles() 不返回任何内容。

函数没有在 python 中声明返回类型,所以如果没有明确的 return 语句,你的函数将返回 None。

def getTxtFiles():
# Create a list of all the .txt files to be searched
    files = []
    for i in os.listdir(os.path.expanduser('~/Documents')):
        if i.endswith('.txt'):
            files.append(i)
    return files <------this is missing in your code-----

推荐阅读