Итерация файла NoneType объект не повторяется в цикле for - PullRequest
0 голосов
/ 28 октября 2018

Я посмотрел другие посты, касающиеся этой TypeError, но они не помогли мне понять это. Там, где происходит ошибка, я пытаюсь просмотреть список возвращенных файлов из функции геотекстиля, а затем найти их для ввода пользователя. Но похоже, что он не может войти в цикл for for in in: из-за NoneType. Что является причиной того, что список файлов не имеет типа?

# 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

Ответы [ 2 ]

0 голосов
/ 28 октября 2018
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
>>>

Исправлено возвращение файлов из 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()
0 голосов
/ 28 октября 2018

Ваш 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-----
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...