文件迭代 'NoneType' 对象在 for 循环中不可迭代

file iteration 'NoneType' object not iterable in for loop

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

# 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

你的 getTextFiles() 没有 return 任何东西。

函数没有在 python 中声明 return 类型,因此如果没有明确的 return 声明,您的函数 returns 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-----
Illustration, issue reproduction.

>>> 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)
...
>>> files = getTxtFiles()
>>> print(files)
None
>>>
>>> for i in files:
...   print 'something'
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
>>>

修复是 return 来自 getTxtFiles() 的文件。

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 getTxtFiles()