Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if valid excel file in python xlrd library

Tags:

python

excel

xlrd

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.

like image 440
Macumbaomuerte Avatar asked Feb 21 '15 11:02

Macumbaomuerte


People also ask

How do you check Excel file is exists or not in Python?

isfile() Method to check if file exists. os. path. isfile() method in Python is used to check whether the specified path is an existing regular file or not.

Does xlrd work with xlsx?

xlrd no longer supports . xlsx files. Use openpyxl to read . xlsx files.

Why does xlrd not support xlsx?

Support for . xlsx files was removed from xlrd due to a potential security vulnerability.


1 Answers

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
like image 77
ndpu Avatar answered Nov 14 '22 22:11

ndpu