使用 xlrd 回溯错误文件名

Traceback with bad filename using xlrd

我正在使用 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'

为什么异常不起作用?我正在测试这个,因为我需要知道文件是否存在,如果不存在,我需要创建它。

您只捕获了 except 子句中的 XLRDError,当文件不存在时会出现 IOError

您可以对两者使用相同的 except 子句:

except(XLRDError, IOError):
    #....

或者,如果您想以不同的方式对待它们,也许更好:

except XLRDError:
    # treat this error
    # ...

except IOError:
    # treat the case where file doesn't exist