0

I am trying to build on example in another question filter directory in python

and trying to add and return the line found along with filename in which it is found. Here is the code

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

I am receiving error

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

any advise? what am I doing wrong?

Community
  • 1
  • 1
x0rcist
  • 23
  • 1
  • 5

1 Answers1

0

If found_in_file hits this line:

return False

a bool is returned. But here

b_found,line = found_in_file(full_name, searchstring)

You expect for two values to be returned. When found_in_file returns, Python thus iterates the returned value to grab the first two values out of it - but it returned a bool, which CAN'T be iterated, and Python gives up and throws an exception: TypeError: 'bool' object is not iterable which is exactly what happened - it tried to iterate a bool to unpack two values from it and could not.

Try return False, None for example.

Patashu
  • 21,443
  • 3
  • 45
  • 53
  • still bit confused. if two values are returned first is boolean and second one is say a string. like v_bool,v_string=found_in_file (name, saerchstring) then why cant python get and assign values to variable it is just saying that v_bool is false i.e. nothing returned and v_string is empty – x0rcist Jun 05 '13 at 23:45
  • @x0rcist No. When you return from found_in_file like this: `return False` you return exactly one value, a boolean `False`. Python wants to assign one value, a boolean `False`, to two variables, `b_found` and `line`. To assign one value to two values, it must be iterable, so it attempts to iterate it and assign the first value to `b_found` and the second value to `line`, but `bool` is not iterable so it throws an error. You can solve this by `returning False,None` because then Python will see that as many arguments are returned as need to be assigned to variables. – Patashu Jun 05 '13 at 23:53