I'm using xlrd 0.9.4 and I would like verify if the file that I must open is valid.
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.
This works fine, the problem is the following. First of all I have a valid .xls file, so script prints Done. Now, assume that the valid .xls file is renamed (also extension), for example from test.xls to 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.
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. In xldr source at lines 18-19 defined a «magic» bytes. First bytes of file compared with this byte sequence at line 85. If its not equal exception will be rise. File extention not involved.
Signatures for different file types can be found there.