9

My scrpt has the following line:

libro_dia = xlrd.open_workbook(file_contents = libro_dia)

When libro_dia is not valid, it raises the following error:

XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '<!DOCTYP'

I whant to handle this error, so I write:

try:
    libro_dia = xlrd.open_workbook(file_contents = libro_dia)
except XLRDError:
    no_termina = False

But it raises the following error:

NameError: name 'XLRDError' is not defined

What's going on?

3 Answers 3

18

You don't have XLRDError imported. I'm not familiar with xlrd, but something like:

from xlrd import XLRDError

might work. Alternatively, qualify your Error when handling it:

try:
    libro_dia = xlrd.open_workbook(file_contents = libro_dia)
except xlrd.XLRDError: #<-- Qualified error here
    no_termina = False

The above is assuming you have the following import:

import xlrd

In response to your comment:

There are several ways to use imports in python. If you import by using import xlrd, then you will have to qualify every object in that module as xlrd.SomeObject. An alternative way is by using the form from xlrd import *, which would allow you to reference the XLRD error without its' module namespace. This is lazy and a bad idea though, as it can lead to namespace clashes. If you would like to reference the error without qualifying it, the correct way to do it would be from xlrd import XLRDError, which would allow you to say except XLRDError. Read more about Python Modules

2
  • It worked, thanks. So I must import xlrd and XLRDError from xlrd
    – José
    Commented Mar 1, 2013 at 14:04
  • Ah, OK, so if I write except: xlrd.XLRDError it also works and I don't need to import XLRDError from xlrd first. Thanks!
    – José
    Commented Mar 1, 2013 at 15:31
4

XLRDError is a custom exception and must be imported to your namespace just like any other object.

Edit: As Burhan Khalid has noted, you could just modify the except block to except xlrd.XLRDError if you already have import xlrd in your module.

1
  • You should expand your answer to include the solution, which is xlrd.XLRDError instead of XLRDError in the except clause. Commented Mar 1, 2013 at 13:49
0

Try using

 xlrd.XLRDError as e and e.message should contain the error string

Sample:

   try:
            workbook = xlrd.open_workbook(sys.argv[1])
   except xlrd.XLRDError as e:
            print e.message
            sys.exit(-1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.