我看过有关此TypeError的其他文章,但他们没有帮助我弄清楚这一点。发生错误的地方是我试图在土工布功能中循环浏览返回文件的列表,然后在其中搜索用户的输入。但是由于无类型,它似乎无法进入“ 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
答案 0 :(得分:1)
您的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-----
答案 1 :(得分:0)
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()