如何检查python xlrd库中是否有效的excel文件

Mac*_*rte 6 python excel xlrd

是否有任何方法使用xlrd库来检查您使用的文件是否是有效的Excel文件?我知道有其他库来检查文件的标题,我可以使用文件扩展名检查.但是为了多平台,我想知道是否有任何我可以在xlrd库中使用的函数,当尝试打开文件然后通知用户时,它可能只返回false之类的东西.

我是Python的新手,所以我尝试调试xlrd.open_workbook函数没有成功.

ndp*_*dpu 11

您可以尝试打开工作簿但在try/except块中捕获XLRDError异常,以防文件格式不受支持:

>>> from xlrd import open_workbook, XLRDError
>>> try:
...     book = open_workbook('test.txt')
... except XLRDError as e:
...     print e
... 
Unsupported format, or corrupt file: Expected BOF record; found '--index-'
Run Code Online (Sandbox Code Playgroud)

或使用简单的功能:

from xlrd import open_workbook, XLRDError

def test_book(filename):
    try:
        open_workbook(filename)
    except XLRDError:
        return False
    else:
        return True
Run Code Online (Sandbox Code Playgroud)