繁体   English   中英

嵌套的 try 语句打开一个 XL 表

[英]Nested try statements to open an XL sheet

我正在尝试在 XL 中打开工作表。 工作表可以命名为“地图”、“地图”或“地图”

这就是我正在做的

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

这看起来很笨重......是否有更多的 pythonic 方式来做到这一点

只需遍历各种可能性,尝试依次打开每一种可能性:

sheet = None
for thing in ['map','Map','MAP']:
  try:
    sheet = book.sheet_by_name(thing)
    break
  except:
    pass

运行后, sheet将设置为可以打开的第一thing 如果无法打开,则sheet将为None

Excel 工作表名称不区分大小写。 Excel 不允许您在单个工作簿中创建多个名称为(地图、Map、MAP、maP 等)的工作表。

candidates = [n for n in book.sheet_names() if n.lower() == 'map']
assert len(candidates) in (0, 1)
if candidates:
     sheet = book.sheet_by_name(candidates[0])
else: 
     whatever()

也许您想提出增强请求,要求 Book.sheet_by_name 使用不区分大小写的搜索。

虽然它不像其他一些方法那样可读,但最短的方法可能是使用:

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

基本上,这使用了通过另一个 SO 答案呈现的列表交集的概念。 可能是一种更简单的创建方法,因此更易于阅读:

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM