繁体   English   中英

使用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 

暂无
暂无

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

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