【发布时间】:2017-07-20 08:55:50
【问题描述】:
我正在使用 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'
为什么异常不起作用?我正在测试这个,因为我需要知道文件是否存在,如果不存在,我需要创建它。
【问题讨论】:
-
你得到的是
IOError而不是XLRDError- 你的处理程序没有捕捉到它。
标签: python excel file file-handling xlrd