简体   繁体   English

xlrd-关于打开文件的问题

[英]xlrd - issue on opening file

I'm using xlrd 0.9.4 and I would like verify if the file that I must open is valid. 我正在使用xlrd 0.9.4 ,我想验证我必须打开的文件是否有效。

To do this, I wrote this code in according with this question : 为此,我根据以下问题编写了此代码:

try:
    book = xlrd.open_workbook(file_path)
    print "Done"
except XLRDError:
    print "Wrong type of file."

where file_path is the path of my file. 其中file_path是我的文件的路径。

This works fine, the problem is the following. 这工作正常,问题如下。 First of all I have a valid .xls file, so script prints Done . 首先,我有一个有效的.xls文件,因此脚本显示Done Now, assume that the valid .xls file is renamed (also extension), for example from test.xls to test.txt. 现在,假设有效的.xls文件已重命名(也是扩展名),例如,从test.xls重命名为test.txt。

If I run the script, i have the same result ( Done ). 如果运行脚本,则结果相同( 完成 )。

Instead, if I use a "real" .txt file (empty or with some text), the script prints Wrong type of file. 相反,如果我使用“真实” .txt文件(为空或带有一些文本),则脚本将打印错误类型的文件。

This behavior happens because the "structure" of the file is not changed? 发生这种现象的原因是文件的“结构”没有更改? Am I doing something wrong? 难道我做错了什么? There is another type of Exception that I can add to except branch? 除了分支,我可以添加另一种异常类型吗?

Thanks in advance 提前致谢

You can see how to xlrd check the file before reading. 您可以了解如何在阅读前对文件进行xlrd检查。 In xldr source at lines 18-19 defined a «magic» bytes. xldr源代码的第18-19行中,定义了一个“魔术”字节。 First bytes of file compared with this byte sequence at line 85. If its not equal exception will be rise. 文件的第一个字节与第85行的该字节序列进行比较。如果不相等,则异常会上升。 File extention not involved. 不涉及文件扩展。

Signatures for different file types can be found there . 可以在此处找到不同文件类型的签名。

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

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