Reputation: 2185
I am processing the data reading from test.xls
file like so:
from sys import exe_info
try:
book = xlrd.open_workbook('test.xls')
sh = book.sheet_by_index(0)
for row in range( 1, sh.nrows ):
for index, value in enumerate(sh.row_values(row)):
process_value(value)
except:
print exc_info()[1]
If an exception is raised while processing the process_value(value)
means there is some thing wrong in that particular row of .xls
file.but when i am printing the exc_info()[1]
I am able to get on the exception description like
'ascii' codec can't encode characters in position 7-10: ordinal not in range(128)
but if I print the exc_info()
function it gives following output
(<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii', u'bokor b\xe3\u0192\xe2\xa9la', 7, 11, 'ordinal not in
range(128)'), <traceback object at 0x01067080>)
So if I want to show exception to user then user is intrested in particular line of that.xls
file which causing error .So in output of exc_info()
I can see the word
u'bokor b\xe3\u0192\xe2\xa9la'
This is the word from XLS file. If we can't show for which line error is raise if I at lease show that above word it will help to find that word and remove that word.
I am not able to get that particular word from exc_info()
or is their is any better way to handle this situation?
Upvotes: 0
Views: 736
Reputation: 83022
xlrd
returns the contents of all text cells as unicode
objects. You don't need to know "the correct encoding" -- it's NOT encoded.
I suggest that you do something like this:
for row in xrange(1, sh.nrows):
for index, value in enumerate(sh.row_values(row)):
try:
process_value(value)
except:
print >> sys.stderr, row, index, repr(value)
raise
That enables you to display all the relevant data, then re-raising the exception so that you get the formatted error message and traceback done for you.
It would probably help us considerably to help you if you were to show us the code for your process_value
function -- are you attempting unicode_object.encode('ascii')
explicitly or implicitly?
Upvotes: 1