(noob alert) why doesn't this work?

Diez B. Roggisch deetsNOSPAM at web.de
Tue Mar 22 12:23:05 CET 2005

> The error thrown is: UnboundLocalError: local variable 'title' referenced
> before assignment

That should be pretty obvious: The UnboundLocalError comes up when you try
to access a variable that hasn't been assigned a value before. E.g try this
in an interactive python session:

foo = "hello"
print foo
print bar     # This will raise UnboundLocalError 

Now in your code, you have a conditional setting of diverse variables. So
only if 

if 'Title' in line:
   title = line[6:-1]

executes, a title is there. Later, you _always_ use title. So you have to do
it like this:

title = "Unknown" # or empty or whatever
if 'Title' in line:
   title = line[6:-1]

Then title will always be there.

The reason that it works for _one_ but not for all is simply that by chance
the one file _had_ a title, but at least one of all the files hadn't. So it
crashes. If you'd only try that file, it would also crash with only one

Diez B. Roggisch

More information about the Python-list mailing list