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

Sign up to request clarification or add additional context in comments.

2 Comments

It worked, thanks. So I must import xlrd and XLRDError from xlrd
Ah, OK, so if I write except: xlrd.XLRDError it also works and I don't need to import XLRDError from xlrd first. Thanks!
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 Comment

You should expand your answer to include the solution, which is xlrd.XLRDError instead of XLRDError in the except clause.
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)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.