Luis Diaz
Luis Diaz

Reputation: 342

Traceback with bad filename using xlrd

I'm using xlrd to open a ".xlsx" file and read the data from it to modify it. If the filename exists everything is ok. but if the file doesn't exists I get a traceback.

The code that I'm using is (just relevant parts):

from xlrd import open_workbook, XLRDError
from xlwt import *
filename = "./resources/tags_meters.xlsx"
bad_filename = "./resources/meters.txt"

# Use this to test bad filenames
filename = bad_filename

and afther that I use a function to read check if the file can be opened:

def test_book(filename):
    try:
        open_workbook(filename)
    except XLRDError as e:
        print "error is" + e.message
        return False
    else:
        return True

if test_book(filename):
    print "Book Ok ... Opening file"
    wb = open_workbook(filename)
else:
    print "Book not opened"

The traceback that I got is:

Traceback (most recent call last):
  File ".\excelread.py", line 38, in <module>
    if test_book(filename):
  File ".\excelread.py", line 31, in test_book
    open_workbook(filename)
  File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 395, in open_workbook
    with open(filename, "rb") as f:
IOError: [Errno 2] No such file or directory: './resources/meters.txt'

Why the exception is not working? I'm testing this because I need to know if a file exists or not, in case not, I need to create it.

Upvotes: 0

Views: 173

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24233

You only catch the XLRDError in your except clause, and an IOError occurs when the file doesn't exist.

You can either use the same except clause for both:

except(XLRDError, IOError):
    #....

Or, maybe better, if you want to treat them differently:

except XLRDError:
    # treat this error
    # ...

except IOError:
    # treat the case where file doesn't exist 

Upvotes: 2

Related Questions