我使用xlrd打开" .xlsx"文件并从中读取数据以进行修改。如果文件名存在,一切正常。但如果文件不存在,我会得到回溯。
我使用的代码(只是相关部分):
from xlrd import open_workbook, XLRDError
from xlwt import *
filename = "./resources/tags_meters.xlsx"
bad_filename = "./resources/meters.txt"
# Use this to test bad filenames
filename = bad_filename
以及我使用函数来检查是否可以打开文件:
def test_book(filename):
try:
open_workbook(filename)
except XLRDError as e:
print "error is" + e.message
return False
else:
return True
if test_book(filename):
print "Book Ok ... Opening file"
wb = open_workbook(filename)
else:
print "Book not opened"
我得到的追溯是:
Traceback (most recent call last):
File ".\excelread.py", line 38, in <module>
if test_book(filename):
File ".\excelread.py", line 31, in test_book
open_workbook(filename)
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 395, in open_workbook
with open(filename, "rb") as f:
IOError: [Errno 2] No such file or directory: './resources/meters.txt'
为什么异常不起作用?我正在测试这个,因为我需要知道文件是否存在,如果没有,我需要创建它。
答案 0 :(得分:2)
您只能捕获except子句中的XLRDError
,并且当文件不存在时会发生IOError
。
您可以对两者使用相同的except子句:
except(XLRDError, IOError):
#....
或者,或许更好,如果你想以不同方式对待它们:
except XLRDError:
# treat this error
# ...
except IOError:
# treat the case where file doesn't exist