Search code examples
pythontry-catchxlrd

Nested try statements to open an XL sheet


I am trying to open a worksheet in XL. The worksheet could be named as 'Map', 'map' or 'MAP'

This is what I am doing

import xlrd
book = xlrd.open_workbook(xls) // where xls is the name of the spreadsheet
try:
     sheet = book.sheet_by_name('map')
except:
     try:
        sheet = book.sheet_by_name('Map')
     except:
        try:
          sheet = book.sheet_by_name('MAP')
        except:
           raise

This looks pretty clunky... is there a more pythonic way of doing this


Solution

  • While it is not exactly as readable as some other methods, probably the shortest way is to use:

    sheet = book.sheet_by_name(list(set(['map', 'Map', 'MAP']) & set(book.sheet_names())[0])
    

    Basically, this uses the concept of list intersection presented via another SO answer. Probably an easier way to create this so it easier to read:

    possibleNames = ['map', 'Map', 'MAP']
    sheetNames = book.sheet_names()
    name = intersect(possibleNames, sheetNames)
    if len(name) < 1:
        print "Error"
        # break program appropiately
    sheet = book.sheet_by_name(name[0])
    
    def intersect(a, b):
        return list(set(a) & set(b))