简体   繁体   中英

How to check if valid excel file in python xlrd library

Is there any way with xlrd library to check if the file you use is a valid excel file? I know there's other libraries to check headers of files and I could use file extension check. But for the sake of multiplatformness I wonder if there's any function I could use in the xlrd library itself that could just return something like false when trying to open the file and then notify the user.

I'm kind of new on Python so I tried getting something debugging the xlrd.open_workbook function with no success.

You can try to open workbook but in try/except block to catch XLRDError exception in case if file format not supported:

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

or use a simple function:

from xlrd import open_workbook, XLRDError

def test_book(filename):
    try:
        open_workbook(filename)
    except XLRDError:
        return False
    else:
        return True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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