python - 文件迭代'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
解决方案
您的 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-----
推荐阅读
- apache-spark - 将 RDD 上传到现有 Cassandra 表时出错
- php - splstack 推送和添加
- fotorama - fotorama 字幕可以是全宽的,带有小的、非扩展的图像吗?
- docker - 自动输入以在 Dockerfile 中选择多个脚本
- php - 从 wp-content .htaccess 中排除特定的 php 文件
- c++ - 使用 c++ builder 5 编译 sqlite 数据库时出错
- django - 从具有多个图像的帖子中编辑图像、图像标题、图像描述
- python - NGINX & UWSGI - 尝试启动服务器时权限被拒绝
- python - 如何使用 ItemAdd 事件监控 Python 中的共享收件箱?
- python-2.7 - 如何在 python 2.7.4 中随机化字典?