0

我正在尝试 在 python 的另一个问题过滤器目录中构建示例

并尝试添加并返回找到的行以及找到它的文件名。这是代码

import os

searchdir = r'C:\Python27\mycode'
searchstring = 'import sys'

def found_in_file(fname, searchstring):
    with open(fname) as infp:
        for line in infp:
            if searchstring in line:
                return True, line
        return False

with open('found.txt', 'w') as outfp:
    count = 0
    search_count = 0
    for root, dirs, files in os.walk(searchdir):
        for name in files:
            count += 1
            full_name = os.path.join(root, name)
            b_found,line = found_in_file(full_name, searchstring)
            if b_found:
                outfp.write(full_name + '\n')
                outfp.writ(line+'\n')
                search_count += 1

print 'total number of files found %d' % count
print 'number of files with search string %d' % search_count

我收到错误

Traceback (most recent call last):
  File "C:/Python27/mycode/fsearch", line 20, in <module>
    b_found,line = found_in_file(full_name, searchstring)
TypeError: 'bool' object is not iterable

有什么建议吗?我究竟做错了什么?

4

1 回答 1

0

如果 found_in_file 命中这一行:

return False

abool返回。但在这儿

b_found,line = found_in_file(full_name, searchstring)

您期望返回两个值。当 found_in_file 返回时,Python 会迭代返回的值以从中获取前两个值 - 但它返回了一个无法迭代的布尔值,Python 放弃并抛出异常:TypeError: 'bool' object is not iterable这正是发生的事情 - 它尝试了迭代一个 bool 以从中解压缩两个值,但不能。

举个return False, None例子。

于 2013-06-05T06:38:48.977 回答