Act Act - 1 year ago 152
Python Question

TypeError: 'bool' object is not iterable, when reading a text file

I'm busy with a Uni project where I need to read text files and ten populate a table with their information. It was working fine last week when I first coded it. Now however, when I try to run it, I get the TypeError: bool, it occurs in my for loop, when I read_ln from the text file, the code is :

from sqlite3 import *
from webbrowser import *

#retrieve a text file
while inc != len(categories):
file_open = open(categories[inc]+'.txt','U')
#assign the category
category = categories[inc]
#run the loop to populate the table popularity
for each_ln in file_open:
#assign the variables.
tab_index = each_ln.find('\t')
PersonNumber = each_ln[0:tab_index]
value = each_ln[tab_index + 1:len(each_ln)]
#populate the database.
TH2_db.execute("INSERT INTO popularity VALUES (?,?,?)" \
, (PersonNumber, category, value))
#increment to move onto the next textfile
inc = inc + 1

Answer Source

Your statements from webbrowser import * at the top of your module imports the function (which opens a new browser window), shadowing the builtin open function (that opens files) which you were intending to call in your later code. returns a Boolean value, rather than a file object, which is what the exception is about.

To fix this, change the import. Either use import webbrowser and qualify the places you use the module (e.g. webbrowser.get() or whatever you're using it for), or import just the specific names that you know you will need (e.g. from webbrowser import get).

Importing with a wildcard is not generally a good idea unless the module you're doing it on is specifically designed for it. This issue shows exactly why.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download