如何检查python xlrd库中是否有效的excel文件 [英] How to check if valid excel file in python xlrd library

查看:735
本文介绍了如何检查python xlrd库中是否有效的excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 xlrd 库来检查您使用的文件是否是有效的Excel文件?我知道还有其他的库来检查文件的头文件,我可以使用文件扩展名检查。但是为了多平台,我想知道在 xlrd 库本身是否有任何功能可以在尝试打开该文件时返回类似false的值,然后通知用户。



我在Python上有一些新功能,所以我尝试了调试 xlrd.open_workbook 函数的东西没有成功。

解决方案

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

 >>>从xlrd import open_workbook,XLRDError 
>>>尝试:
... book = open_workbook('test.txt')
...除了XLRDError作为e:
...打印e
...
不支持的格式或损坏的文件:预期的BOF记录;发现'--index-'

或使用一个简单的功能:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $



$
除XLRDError外:
返回False
其他:
返回True


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

这篇关于如何检查python xlrd库中是否有效的excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆